1.1.1 Summary
Now, we can often see complex JavaScript applications.ProgramAs these applications become more and more complex, a long string of jquery callback statements or different function calls are executed by applications in different states, these practices will become unacceptable, as a result, JavaScript developers began to look for a development method with better organization and efficiency.
One of the most common architecture modes to achieve organization and efficiency is the well-known Model View Controller (MVC) model, this mode encourages developers to divide different parts of their applications into modules that are easier to manage. Instead of using a function to directly call the database, we create a model (model or entity) to manage the database. You can use a template or view to simplify the display.CodeFinally, the controller is used to process the requests of our applications. The MVC mode minimizes the Coupling Degree between each module and provides the development efficiency of the program.
The well-known JavaScript MVC frameworks include Ember. JS, backbone. JS, Knockout. JS, spine. JS, Batman. JS, and angular. js.
Figure 1 JavaScript MVC Framework
Through this, we can clearly understand the differences between the features, complexity, and learning curves of JavaScript MVC frameworks. From left to right, we can see whether various JavaScript MVC frameworks support data binding) templates, persistence, and other features increase the complexity of the MVC Framework from bottom to top. To be honest, I have not compared the advantages and disadvantages of each framework, if you have made a comparison or readArticleWe will not be enlightened.
In the next blog, we will introduce the use of Ember. js.
Directory
- MVC Definition
- Set ember
- Template (handlebars)
- Application)
- Routing)
- Model)
1.1.2 text
Ember. JS is a javascript MVC framework that evolved from the rename of sproutcore 2.0 created by Apple's former employee. ember has been released to 1.0.0-RC.3.
MVC Definition
Before introducing ember, let's first review the MVC pattern. Here we will introduce the role of MVC pattern in programming through an example, for example:
1. the user performs an operation, such as hitting the keyboard or clicking the mouse button.
2. The controller receives the input and triggers a message to the model ).
3. The model modifies the content of a message (CRUD operation ).
4. View monitors changes in the model and displays corresponding updates on the user interface.
Through the above, we learned the role and connection between various components in MVC. After learning about the MVC mode, we can make it clearer whether JavaScript MVC frameworks need to be introduced in our project.
When building an ember application, we use six main components: application, model, view, and template) routing and controller ).
Next, we will introduce the use of Ember by implementing a specific program.
Set ember
First, we need to reference a series of JavaScript libraries, So we add JS files in the program and save the following JS files 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
Renewal page.
<! Doctype Html > < Html > < Head > < Meta HTTP-equiv = "Content-Type" Content = "Text/html; charset = UTF-8"/> < Meta HTTP-equiv = "Description" Content = ""/> < Meta Name = "Description" Content = ""/> < Meta Name = "Keywords" Content = ""/> < Meta Name = "Author" Content = ""/> < Title > </ Title > < Link REL = "Stylesheet" Href = "" Type = "Text/CSS"/> < Link REL = "Stylesheet" Href = "" Type = "Text/CSS"/> </ Head > < Body > <! -- Add JavaScript libs reference --> < Script SRC = "// Ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </ Script > < Script SRC = "JS/libs/handlebars-1.0.0-rc.3.js"> </ Script > < Script SRC = "JS/libs/ember-1.0.0-rc.2.js"> </ Script > < Script SRC = "JS/libs/ember-data.js"> </ Script > < Script SRC = "JS/APP. js"> </ Script > </ Body > </ Html >
Now we have implemented the first ember program, but it does not have specific features. Next, we will add features to the program.
Template (handlebars)
Ember. JS uses the handlebars template engine. Before getting started, let's briefly introduce handlebars. JS. If you have used jquery templates or other script templates, you can understand handlebars. the use of JS is not too difficult, and you don't have to worry if you have never used it, Because handlebars. JS is also quite simple to use.
It allows developers to mix the original HTML and handlebars expressions to generate and render the corresponding html. The expressions are included in, we can load the handlebars template to the page in two ways. We can directly embed the HTML page and add the script tag of the text/X-handlebars type to the page; or save it to a file suffixed with handlebars or Harvard, and then use Ember. load js to the page.
For the sake of simplicity, we directly embed the handlebarsscript into the index.html page.
<ScriptType= "Text/X-handlebars"Data-template-name= "Application"><H1> employee System </H1 >{{ outlet }}</Script>
In the preceding example, the template application is defined and the handlebars expression {outlet} is added. It acts like a placeholder and tells ember that the content here should be dynamically loaded into the page, when we open the index page in the browser, the information in the template is not displayed.
Application)
This is because we have not defined the Ember program. Each ember application requires an ember application instance. Let's create the first ember application instance in APP. js!
First, create an ember application instance. The specific implementation is as follows:
// Creates an application instance.APP = Ember. application. Create ();
We have defined an ember application named app. Of course, we can name the application as any one, however, Ember requires that the names of variables start with an uppercase letter.
Now, open the page in the browser to display the information loaded by the template.
Figure 2 index page
Some may ask how ember knows which templates need to be loaded? More importantly, we didn't tell ember the name of the template to be loaded. We just embedded the template application into the page.
In fact, here is a "Potential Rule": if we do not define applicationview (application view), ember will automatically generate an applicationview and load the template named application by default. Suppose, if we rename the template as application1, the default applicationview cannot find the template to be loaded.
Of course, you can also define applicationview to specify the name of the template to be loaded. The specific implementation is as follows:
// Defines an application view, then loading // relative templates.App. applicationview = Ember. View. Extend ({templatename:'Application1'});
Now, we have another question: How do I load the content in the expression {outlet?
Routing)
Because the content of {outlet} is the template content dynamically obtained after route selection, we first introduce the routing of the Ember program, it can help manage the state of the application and the resources required for user navigation. When our application is started, the routing is responsible for displaying the template, loading data, and managing the status of the application.
Now, we define the application route by specifying the URL. The specific definition is as follows:
// 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"});});
The preceding two routes are defined: Home and employee, the global route of the application, and the template that simultaneously accesses the home route, data, and application status are loaded on the index page; the employee route accesses the basic information of each employee according to the employee ID.
Next, we define the home template. The specific implementation is as follows:
<ScriptType= "Text/X-handlebars"Data-template-name= "Home"><H3> employee information </Script>
Above, we defined the home template and used the each expression to iteratively access the elements in the employeeinfo object. At this moment, we have another question: Where can we get the employeeinfo object?
Previously, we mentioned that the Controller is responsible for retrieving data from the model and loading and displaying data through the template. Then, we can get data through the explicit city-defined controller. If we do not define the data, ember automatically generates a homecontroller.
// Defines a custom controll.App. homecontroller = Ember. Controller. Extend ({employeeinfo :['Jackson Huang','Ada li','Jk rush']});
Above, we have customized homecontroller and initialized the employeeinfo array. Now let's refresh the index page.
Figure 3 index page
Now, we have another question. If our program has a lot of resources to access, do we explicitly define the controller?
In fact, we can also define the routing controller to automatically select the controller, and ember will automatically generate the corresponding controller without writing any code, the specific implementation is as follows:
// Defines a routing handler.App. homeroute = Ember. route. Extend ({model:Function(){Return['Jackson Huang','Ada li','Jk rush'] ;}, Setupcontroller:Function(Controller, model) {controller.Set('Content', Model )}});
Now we have defined the routing controller app. homeroute and the method setupcontroller is rewritten. It receives the Controller matched by the route handler as the first parameter, namely homecontroller. Then we pass the model parameter to homecontroller, then homecontroller can obtain the corresponding data and load it to the template for display.
Above, we successfully loaded the data to the page, but the data is directly hardcode in the Controller. We didn't define a model to get the data.
Next, we will get data from fixtures, then we need to use the ember-data.js library, the specific implementation is as follows.
// Customs a store.App. Store = Ds. Store. Extend ({// Configure y the version of Ember data API used.Revision: 12,// Used fixtureadapter.Adapter:'Ds. fixtureadapter'});
Above, we are in app. define Ds in Js. store subclass app. store, and declare that the version of our program using the Ember data API is 12, when the API version is updated or the version used is too old, the ember-data.js will return the corresponding error message.
For example, the current ember-data.js version is 12. If we define version 1 API in APP. JS, we will see the following error message in the console.
Figure 4 ember-data.js version info.
Model)
A model is an object that represents application data, which may be a simple array or data that is dynamically retrieved through restful APIS; An ember-data.js provides APIs for loading, ing, and updating application models.
The ember-data.js provides storage space for each application, keeping loaded models and retrieving models that are not yet loaded.
Previously, we defined the application app. Now, we need to provide the program with data, that is, employee information. Therefore, we need to create the program model (entity) employee, next we will define the model.
// Defines a employee model.App. Employee = Ds. model. Extend ({Name: Ds. ATTR ('String'), Department: Ds. ATTR ('String'), Title: Ds. ATTR ('String')})
The above defines the employee model, which inherits Ds. Model and contains three fields: name, department, and title.
Next, we define app. employee. Fixtures to simulate obtaining data from the server.
// 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 a series of basic information about employees.
Next, modify home and add the employee template. The specific implementation is as follows:
<! -- Home temp start --> < Script Type = "Text/X-handlebars" Data-template-name = "Home"> <H3> employee information </ Script > <! -- Home temp end --> <! -- Employee temp start --> < Script Type = "Text/X-handlebars" Data-template-name = "Employee"> <Div> </ Script > <! -- Employee temp end -->
In the home template, we add an each expression to iteratively access the employee element, and then select the employee route through linkto. Then, the employee information is displayed in the employee template according to the route selection.
Figure 5 program page
Now, we have completed the basic functions of the Employee Program and provided users to check employee information.
1.1.3 Summary
This article uses demo examples to introduce the use of Ember. It mainly introduces the Ember model, controller, template, and routing. Since Ember is a javascript MVC framework, as a beginner, it is easy to get confused about its automatic generation and default rules. Therefore, I strongly recommend that you read the official documents of routing and controller carefully.
By introducing the handlerbars template engine of Ember, we define the demo program page, then define the routing behavior through the routing controller, select the Controller Based on the routing behavior, and the Controller is responsible for data loading and display. However, the Ember View module has not been designed in our example. For more information, see Official documents 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