Ember. js implements single-page applications

Source: Internet
Author: User

1.1.1 Summary

A single-page application (SPA) is a Web application that loads a single HTML page and dynamically updates the page when the user interacts with the application.

SPA uses AJAX and HTML5 to create fluent and responsive Web applications, and does not frequently reload pages. However, this means a lot of work is done in the client's JavaScript. This leads to the need to program more Javascript code in the client to handle data interaction issues. Fortunately, we can use many open-source JavaScript frameworks to simplify the creation of SPA tasks, for example, Ember, Backbone, Angular, Knockout, DurandalJS, and Hot Towel.

Directory
  • Create an ASP. net mvc Project
  • Server Model
  • RESTful Service
  • Ember Application
  • Ember Model
  • Ember Controller
  • Ember Route
  • Ember Template
1.1.2 text

Ember is a powerful JavaScript MVC framework that is used to create complex Web applications, eliminate samples, and provide a standard application architecture, it supports user interface binding, view, and Web presentation layer, and works well with other frameworks. To create a real-time interactive Web application, ASP is used here.. net mvc rest service.

MVC Concept

I believe you are not familiar with the MVC mode. Here we will briefly introduce the MVC mode: it is designed to separate views, models, and controllers. The model is used to store data, A view is used to display applications to users. A Controller acts as a bridge between a model and a view.

Ember implements the MVC mode, including View, Controller, Router, Template, and Model. Next, we will introduce the combined use of Ember and Web APIs by implementing a single page application.

Create an ASP. net mvc Project

First, create an ASP. net mvc 4 Web application, and then select the project template Web API. In this case, Ember is not used for simplicity. if you want to use or learn about js templates, please download them here.

Next, we add the reference Script file ember in the Script folder. js, ember-data.js, handlebars-1.0.0.js and jquery-2.0.3.js, and then create the app file, it is used to store the client script file, we create application. js, models. js, routes. js and controllers. js file.

Now, we implement ASP. net mvc application to provide server-side APIs. Single-page applications call our API to operate data. Next, we will provide specific implementation methods.

Server Model

Next, create a data transmission class Employee in the Models file, which is defined as follows:

{    Id { ; ; }    FirstName { ; ; }    LastName { ; ; }    Title { ; ; }    Department { ; ; }    Remarks { ; ; }}

Next, we use EF6 for data persistence. We know that there are three programming modes for EF:

  • Database First: Database First
  • Model First: Model First
  • Code First: Code First

Previously, we have defined the data transmission object Employee, but we have not defined a data table, so we will use the Code First model to create a data table.

Next, we will define the EmployeesContext type as follows:

: DbContext{    EmployeesContext()        : ()    {    }    DbSet<Employee> Employees { ; ; }}

In the constructor EmployeesContext (), we define the database connection name as EmployeesContext. Next, we need to add the corresponding database connection in the Web. config file. The specific definitions are as follows:

"" "" "" 
RESTful Service

Next, we need to provide interfaces for client programs to call. Therefore, we create the rest api web Controller EmployeesController in the Controller file, which inherits from ApiController and defines the GetEmployeesBy () method () and PutEmployee () are defined as follows:

HTTP verb

URI

Description

GET

/Api/employees

Retrieve the list of all employees

GET

/Api/employees/{id}

Obtain employee information with ID equal to {id}

PUT

/Api/employees/{id}

Update employee information with ID equal to {id}

POST

/Api/employees

Add new employee information to the database

DELETE

/Api/employees/{id}

Delete employee information from the database

Table 1 REST API

async Task<IHttpActionResult> PutEmployee(id, Employee employee){    (!ModelState.IsValid)    {        BadRequest(ModelState);    }    (id != employee.Id)    {        BadRequest();    }    db.Entry(employee).State = EntityState.Modified;    {        await db.SaveChangesAsync();    }    (DbUpdateConcurrencyException)    {        (!EmployeeExists(id))        {            NotFound();        }        ;    }    Ok();}

Previously, we implemented the rest api to provide interfaces GetEmployeesBy () and PutEmployee (). The client places the type in the URI query string for calling. For example, to obtain information about all employees of the IT department, the client sends an Http GET request/api/employees? Department = IT, then the Web API automatically binds the query parameters to the GetEmployeesBy () method.

Some may wonder: "How does a Web API automatically BIND queries to different API methods ?" First, we need to know that the client sends an Http request to call the Web API. When our Web API receives an Http request, it will bind a specific method according to the route selection.

Next, let's take a look at the implementation of the default routing method. The specific definition is as follows:

Register(HttpConfiguration config){    config.Routes.MapHttpRoute(        name: ,        routeTemplate: ,        defaults: { id = RouteParameter.Optional }    );}

The default routing implementation has been provided in the WebApiConfig class. Of course we can also implement this method again, but we still use the default routing method here.

For example, the client sends an Http request/api/employees? Department = IT. The route selection will go to the EmployeesController to find the department method parameter, and then bind the method to call.

Now we have implemented the server-side rest api. Next, we will create a database table through the Code First mode of EF.

Our program uses EF 6 and Web API 5.0. You can enter the following command in the package management console to install the program.

  • Install-Package Microsoft. AspNet. WebApi-Version 5.0.0
  • Install-Package EntityFramework-Version 6.0.2

We can also use the Update-Package password to Update all packages. Code First migration has three main commands:

  • Enable-Migrations: enables migration.
  • Add-Migration: builds a base frame for the next Migration based on the changes you have made to the model since the last Migration was created.
  • Update-Database: Apply all pending migrations to the Database.

When data migration is enabled successfully, the Migrations file will be added to our project and the corresponding database table will be generated in our database.

Previously, we created an ASP. net mvc application to provide server-side APIs. Let's implement the Ember client. For more information about Ember, see here.

Ember Application

First, create an Ember application in the application. js file, which is defined as follows:

window.App = Ember.Application.create({    LOG_TRANSITIONS: ,    LOG_TRANSITIONS_INTERNAL: });
Ember Model

Next, we need to create a data storage object (Employee) in the client, which is defined as follows:

App.Employee = DS.Model.extend({    Id: DS.attr(),    FirstName: DS.attr(),    LastName: DS.attr(),    Title: DS.attr(),    Department: DS.attr(),    Remarks: DS.attr(),});

In the previous section, we have defined the server-side data model Employee. Because the RESTful service only returns objects in JSON format, to facilitate binding the data model to the view, we need to define an Ember data model Employee corresponding to the server in the client.

Ember Controller

The Controller is defined in Scripts/app/controllers. js. If we want to represent a single model (a single Employee object), we can inherit the ObjectController.

If we represent multiple models (a series of Employee objects), we need to inherit ArrayController.

App.EmployeesController = Ember.ArrayController.extend();App.EmployeeController = Ember.ObjectController.extend({    isEditing: ,    actions: {        edit: () {            .(, );        },        save: () {            .content.save();            .(, );        },        cancel: () {            .(, );            .content.rollback();        }    }});

The preceding two controllers are defined: EmployeeController and EmployeesController. In EmployeesController, we implement the event handling method. When you click save, call the save () method. Then, we need to define the serialized data of the EmployeeAdapter object and call the Web API method to save the data.

App.EmployeeAdapter = DS.RESTAdapter.extend({    updateRecord: (store, type, record) {        data = store.serializerFor(type.typeKey).serialize(record);        .ajax(.buildURL(type.typeKey, data.Id), , { data: data });    },    : });

The updateRecord () method is implemented to obtain the data submitted by the user for serialization, and then call the Web API to save the data.

Ember Route

Routing is defined in Scripts/app/routes. js. Here we define the routes of the services and about.

App.Router.map(() {    .route();    .resource(, () {        .route(, { path: });    });});
Ember Template

We know that Ember uses the Handlebars template engine, and the template we define is based on the Handlebars syntax. If you have used jQuery templates or other script templates, you can master 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.

First, we define six templates, namely application, about, deployments, deployments/employees, _ employees, and error.

Application. Harvard: the default template loaded when the application starts.

About. HBr: the "/about" routing template.

Departments. Harvard: the template for "/departments" routing. The Department navigation bar is displayed.

Deployments/employees. Harvard: the template for the "/deployments/employees" route. All user information is obtained based on the department.

_ Employees, receives a template as its parameter and renders it properly (For details, refer to here ).

Error: a template for some current error messages.

<!-- application START -->    <script type=data-template-name=>      <div =>             In the preceding section, we define application, about, deployments, deployments/employees, _ employees, and error, respectively. In the deployments/employees template, the partial method is used to pass the simulation to the _ employee template in the form of parameters.

 

Now, we have completed the Ember single page application. Here I would like to recommend a Chrome plug-in for Ember Inspector, which makes it easier for us to understand the Ember template, the relationship between routing and control improves our development efficiency.

1.1.3 Summary

Through the implementation of a single page application, we introduce the combined use of Ember and Web APIs. In fact, the concept of controller, view, model and routing in Ember and ASP. net mvc is very similar, if we have ASP. net mvc programming experience, so there is not much difficulty in mastering the use of Ember. This article only introduces Ember. js basic knowledge. If you want to learn more, we recommend that you go to the official forum to learn or refer to relevant articles.

Finally, I wish you a happy New Year, good health, family happiness, Code with pleasure.

Reference
  • Http://www.cnblogs.com/rush/archive/2012/05/15/2502264.html
  • Http://msdn.microsoft.com/en-us/data/jj591621
  • Http://msdn.microsoft.com/zh-cn/data/jj591621.aspx
  • Http://www.asp.net/single-page-application/overview/templates/emberjs-template
  • Http://www.codeproject.com/Articles/511031/A-sample-real-time-web-application-using-Ember-js
  • Http://msdn.microsoft.com/zh-cn/magazine/dn463786.aspx

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.