"Javsscript" Ember.js

Source: Internet
Author: User
Tags create index uppercase letter

Now, we can often see complex javascript applications, because these applications become more complex, a long list of jquery callback statements or through the application in various states to perform different function calls, these practices will become no longer acceptable, This has led JavaScript developers to start looking for a more organized and more efficient way to develop.

One of the most common architectural patterns for organization and efficiency is the model View Controller (MVC) pattern we know, which encourages developers to split different parts of their applications into more manageable modules, and we don't have to use a function to call the database directly. The database is managed by creating a model (the models or entities), the display code is simplified through templates (template) or Views (view), and finally, by using the controller to process requests for our applications, The MVC pattern minimizes the degree of coupling between each module and provides the development efficiency of the program.

Our familiar JavaScript MVC frameworks are: Ember.js, Backbone.js, Knockout.js, Spine.js, Batman.js, and Angular.js.

Figure 1 Javascript MVC Framework

Through, we can clearly understand the characteristics of JavaScript MVC framework, complexity and learning curve differences, from left to right we understand that each JavaScript MVC framework supports data binding, Templates (templating) and persistence features, from bottom to top, the complexity of the MVC framework increases, to tell the truth I did not compare the pros and cons of each frame, if you have done the relevant comparison or read about the article also generous enlighten.

In the next blog post, we'll cover the use of ember.js.

Directory
    • MVC definition
    • Set Ember
    • Templates (Handlebars)
    • Applications (application)
    • Routing (Routing)
    • Models (model)
1.1.2 Body

Ember.js is a JavaScript MVC framework that evolved from the renaming of Sproutcore 2.0 created by Apple's former employees, Ember has been published to 1.0.0-rc.3.

MVC definition

Before introducing Ember, let's review the MVC pattern, and let's look at an example of how the MVC pattern works in programming, such as:

1. The user performs an action, such as tapping on the keyboard or clicking the mouse button.

2. The controller receives input and triggers a message to the model.

3. The model modifies its contents (CRUD operations) based on the message.

4. The view monitors changes in the model and renders the corresponding updates to the user interface.

Through the above, we understand the roles and linkages between the various parts of MVC, and after understanding how the MVC pattern works, we can be more specific about whether we need to introduce JavaScript's MVC framework into our projects.

When building ember applications, we use six main parts: Applications (Application), models, views, templates (template), routing (Routing), and controllers.

Next, we will introduce the use of Ember by implementing a specific program.

Set Ember

First, we need to refer to a series of JavaScript libraries, so we add the JS file to the program and save the following JS file to this folder:

Ember.js:ember 1.0.0-rc.3

Ember-data.js:revision 12

Handlebars.js:handlebars 1.2.rc.3

Jquery.js:jQuery 1.9.1

App.js: Our application code

Above, we save a series of JS files to the local, of course, we can also use the CDN (Content distribution network) to obtain the corresponding JavaScript library, next, let us create index.html page.

<! DOCTYPE html>

Now that we've implemented the first Ember program, but it doesn't have a specific function, we'll add functionality to the program next.

Templates (Handlebars)

Ember.js using the handlebars template engine, before we begin to use, let us first briefly introduce handlebars.js, if you have used jquery template or other script template, then there is no great difficulty in mastering the use of handlebars.js, if Did not use or worry, because the use of handlebars.js is quite simple.

It allows the developer to mix the original HTML and handlebars expressions to produce the corresponding HTML, and the expression to be included in the {{}}, we can load the handlebars template into the page in two ways, we can directly embed the HTML page, By adding a script tag of type text/x-handlebars to the page, or by saving it to a file that is suffixed with handlebars or HBS, and then loading it into the page by Ember.js.

For the sake of simplicity, we embed the handlebars script directly into the index.html page.

<script type= "Text/x-handlebars" data-template-name= "Application" >        

Above, we defined the template application, and added the handlebars expression {{outlet}}, which acts like a placeholder, telling Ember that the content here is dynamically loaded into the page, When we open the index page in the browser, the information in the template is not displayed.

Applications (application)

This is because we have not defined the Ember program, each ember application needs a Ember application instance, then let us create the first Ember application instance in App.js!

First, we create a Ember application instance, which is implemented as follows:

Creates an application instance. APP = Ember.Application.create ();

Above, we define a ember application called app, of course we can name the program arbitrary, but one thing we should note is that Ember requires the name of the variable to start with an uppercase letter.

Now that we have the page open in the browser, we can display the information loaded by the template.

Figure 2 Index page

Maybe someone will ask Ember how to know which templates need to be loaded? More importantly, we did not tell Ember the name of the template to load, we just embed the template application into the page directly.

In fact, there is a "unspoken rule": if we do not define Applicationview (application view), then Ember will automatically generate a Applicationview and default loading template named application, assuming that If we rename the template to Application1, the default applicationview will not find the template to load.

Of course, we can also specify the name of the template that needs to be loaded by defining the Applicationview, specifically implementing the

Defines an application view and then loading//relative templates. App.applicationview = Ember.View.extend ({  templatename: ' Application1 '});

Now, we have another question: how does the content in the expression {{outlet}} load the display?

Routing (Routing)

Since the contents of {{outlet}} are dynamically obtained from the template content based on the routing selection, we first introduce the route of the Ember program, which can help manage the resources that should be the state of the program and the resources required for the user to navigate, and when our application starts, the route is responsible for displaying the template, loading the data, and managing the state of the application.

Now, we define the route of the application by specifying the URL semantics, as defined below:

Defines a goal routing home and//The detail information of employee routing. App.Router.map (function () {    This.route ("Home", {path: "/"});    This.route ("employee", {path: "/employee/:employee_id"});

Above, we defined two routes: The application's global routing home and employee, loading the home route's template, data, and application status on the index page, while the employee routing will be based on the Employee_ ID Access basic information for each employee.

Next, we define the home template, which is implemented as follows:

<script type= "Text/x-handlebars" data-template-name= "Home" >        

Above, we define the home template and use each expression to iterate over the elements in the EmployeeInfo object, and then we have another question: Where do the EmployeeInfo objects get from?

Earlier, we mentioned that the Controller is responsible for getting the data from the model and then loading the display through the template, then we can get the data by the explicit city definition controller, if we do not define it, Ember will automatically generate a homecontroller.

Defines a custom controll. App.homecontroller = Ember.Controller.extend ({      employeeinfo: [' Jackson Huang ', ' Ada Li ', ' JK Rush ')};

Above, we have customized the HomeController and initialized the EmployeeInfo array, now we refresh the index page.

Figure 3 Index page

Now, we have another question, if we have a lot of resources to access the program, then we have to explicitly define the controller?

In fact, we can also define the routing controller to automate the selection of the controller, and Ember will automatically generate the corresponding controller without us to write any code, the implementation of the following:

  Defines a routing handler.  App.homeroute = Ember.Route.extend ({    model:function () {     return [' Jackson Huang ', ' Ada Li ', ' JK Rush ');   },< C6/>setupcontroller:function (Controller, model) {        controller.set (' content ', model)}  });

Right now We define the routing controller App.homeroute and override the method Setupcontroller, which receives the controller that the route handler matches as the first parameter, namely HomeController, and then we pass the model parameter to HomeController, then Homeco Ntroller can get the corresponding data and load it into the template to show it.

Above, we successfully loaded the data into the page, but the data was directly hardcode in the controller, we did not define the model to get the data.

Next, we will implement the data from the fixtures, when we need to use the Ember-data.js library, specifically implemented as follows.

Customs a store. App.store = DS. Store.extend ({  //Notify The version of the Ember Data API used.  Revision:12,  //used Fixtureadapter.  Adapter: ' DS. Fixtureadapter '});

Above, we define Ds.store subclass App.store in App.js, and affirm that our program uses the Ember Data API version is 12, when the API version is updated or the version used is too old, Ember-data.js will return the corresponding error message.

For example: The current Ember-data.js version is 12, and if we define the API using version 1 in App.js, we will see the following error message in the console.

Figure 4 Ember-data.js version information

Models (model)

A model is an object that represents an application's data, which may be a simple array or dynamically retrieved data through a RESTful API; Ember-data.js provides an API to load, map, and update the application model.

Ember-data.js provides storage space for each application, and storage space is responsible for keeping the loaded model and retrieving the model that has not yet been loaded.

Earlier, we defined the app app, and now we need to give the program data that is employee information, so we're going to create the model (entity) employee for the program, and then we'll implement the model definition.

Defines a employee model. App.employee = DS. Model.extend ({  name:DS.attr (' string '),  department:DS.attr (' string '),  title:DS.attr (' string ')})

Above, we define the employee model, which inherits the Ds.model and contains three fields, respectively, Name,department and title.

Next, we simulate getting data from the server side by defining App.Employee.FIXTURES.

Defines a JSON array. App.Employee.FIXTURES = [{  id:1,  name: ' Jackson Huang ',  Department: ' IT ',  title: ' Programmer '},{  Id:2,  name: ' Ada Chen ',  Department: ' Purchasing ',  title: ' Buyer '},{  id:3,  name: ' JK Rush ',  department: ' It ',  title: ' Programmer '},{  id:4,  name: ' Lucy Liu ',  department: ' It ',  title: ' Tester '},{  id:5,  name: ' Julia Liu ',  Department: ' HR ',  title: ' Manager '}];

Above, we define the JSON array App.Employee.FIXTURES, which contains the basic information of a series of employees.

Next, we modify the home and add the employee template, which is implemented as follows:

<!--Home temp START--><script type= "Text/x-handlebars" data-template-name= "Home" > 

In the home template, we add each expression iteration to access the employee element, and then select the employee route through Linkto, and then display the employee information in the employee template based on the route selection.

Figure 5 Program page

Now we have completed the basic functions of the employee program, providing users with information about their employees.

1.1.3 Summary

This paper introduces the use of Ember by demo example, mainly introduces Ember model, controller, template and route, because Ember is the JavaScript MVC framework, and as a beginner it is easy to confuse it with the automatic generation and default rules, So I highly recommend that you take a closer look at the official documents of Routing and controller.

By introducing the Handlerbars template engine of Ember, we define the page of the demo program, then define the routing behavior through the routing controller, select the controller according to the routing behavior, and the controller is responsible for loading and displaying the data. However, we have not yet designed the Ember view module in our example, if you would like to learn more, please refer to the official documentation or books.

Reference
    • Http://www.adobe.com/cn/devnet/html5/articles/flame-on-a-beginners-guide-to-emberjs.html
    • Http://net.tutsplus.com/tutorials/javascript-ajax/getting-into-ember-js/?search_index=3
    • http://emberjs.com/guides/
    • http://xbingoz.com/emberguides/0.php
    • Http://andymatthews.net/read/2012/03/07/Getting-Started-With-EmberJS

Http://www.cnblogs.com/rush/archive/2013/04/29/3051191.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.