"
ASP.NET (snapshot 2017) Microsoft documentation and samples

EmberJS template

by Xinyang Qiu

The EmberJS MVC Template is written by Nathan Totten, Thiago Santos, and Xinyang Qiu.

Download the EmberJS MVC Template

The EmberJS SPA template is designed to get you started quickly building interactive client-side web apps using EmberJS.

“Single-page application” (SPA) is the general term for a web application that loads a single HTML page and then updates the page dynamically, instead of loading new pages. After the initial page load, the SPA talks with the server through AJAX requests.

AJAX is nothing new, but today there are JavaScript frameworks that make it easier to build and maintain a large sophisticated SPA application. Also, HTML 5 and CSS3 are making it easier to create rich UIs.

The EmberJS SPA Template uses the Ember JavaScript library to handle page updates from AJAX requests. Ember.js uses data binding to synchronize the page with the latest data. That way, you don’t have to write any of the code that walks through the JSON data and updates the DOM. Instead, you put declarative attributes in the HTML that tell Ember.js how to present the data.

On the server side, the EmberJS template is almost identical to the KnockoutJS SPA template. It uses ASP.NET MVC to serve HTML documents, and ASP.NET Web API to handle AJAX requests from the client. For more information about those aspects of the template, refer to the KnockoutJS template documentation. This topic focuses on the differences between the Knockout template and the EmberJS template.

Create an EmberJS SPA Template Project

Download and install the template by clicking the Download button above. You might need to restart Visual Studio.

In the Templates pane, select Installed Templates and expand the Visual C# node. Under Visual C#, select Web. In the list of project templates, select ASP.NET MVC 4 Web Application. Name the project and click OK.

In the New Project wizard, select Ember.js SPA Project.

EmberJS SPA Template Overview

The EmberJS template uses a combination of jQuery, Ember.js, Handlebars.js to create a smooth, interactive UI.

Ember.js is a JavaScript library that uses a client-side MVC pattern.

In addition, the Ember Data library can be used to synchronize JSON objects (obtained from the server through a RESTful API) and the client models.

The EmberJS SPA template organizes the scripts into eight layers:

Let’s look at some of these scripts in more detail.

Models

The models are defined in the Scripts/app/models folder. There are two model files: todoItem.js and todoList.js.

todo.model.js defines the client-side (browser) models for the to-do lists. There are two model classes: todoItem and todoList. In Ember, models are subclasses of DS.Model. A model can have properties with attributes:

[!code-javascriptMain]

   1:  todoItemId: attr('number'), 
   2:  title: attr('string')

Models can define relationships to other models:

[!code-cssMain]

   1:  todoList: DS.belongsTo('App.TodoList'),

Models can have computed properties that bind to other properties:

[!code-javascriptMain]

   1:  hasError: function () {
   2:      var currentError = this.get("error");
   3:      return !(currentError === '' || currentError === null);
   4:  }.property('error'),

Models can have observer functions, which are invoked when an observed property changes:

[!code-javascriptMain]

   1:  saveCheckbox: function () {
   2:      if(this.get("isDirty")){
   3:          if (this.get("todoItemId")) {
   4:              App.store.commit();
   5:          }
   6:      }
   7:  }.observes('isDone'),

Views

The views are defined in the Scripts/app/views folder. A view translates events from the application UI. An event handler can call back to controller functions, or simply call the data context directly.

For example, the following code is from views/TodoItemEditView.js. It defines the event handling for an input text field.

[!code-javascriptMain]

   1:  App.TodoItemEditView = Em.TextField.extend({
   2:      lastValue: '',
   3:      focusIn: function (evt) {
   4:          this.lastValue = this.get('parentView').templateData.view.content.get("title");
   5:      },
   6:      focusOut: function (evt) {
   7:          this.changeContent();
   8:      },
   9:   
  10:      insertNewline: function (evt) {
  11:          $(evt.target).blur();
  12:      },
  13:   
  14:      changeContent: function () {
  15:          var todoItem = this.get('parentView').templateData.view.content;
  16:          var newValue = todoItem.get("title");
  17:          if (this.lastValue != newValue) {
  18:              App.store.commit();
  19:              this.lastValue = newValue;
  20:          }
  21:      }
  22:  });

Controller

The controllers are defined in the Scripts/app/controllers folder. To represent a single model, extend Ember.ObjectController:

[!code-javascriptMain]

   1:  App.TodoItemController = Ember.ObjectController.extend({
   2:  });

A controller can also represent a collection of models by extending Ember.ArrayController. For example, the TodoListController represents an array of todoList objects. The controller sorts by todoList ID, in descending order:

[!code-javascriptMain]

   1:  App.TodoListController = Ember.ArrayController.extend({
   2:      error: "",
   3:      sortProperties: ['todoListId'],
   4:      sortAscending: true,
   5:   
   6:      // ...

The controller defines a function named addTodoList, which creates a new todoList and adds it to the array. To see how this function gets called, open the template file named todoListTemplate.html, in the Templates folder. The following template code binds a button to the addTodoList function:

[!code-htmlMain]

   1:  <input type="button" {{action "addTodoList"}} class="isActive" value="Add Todo list"></input>

The controller also contains an error property, which holds an error message. Here is the template code to display the error message (also in todoListTemplate.html):

[!code-htmlMain]

   1:  <p class="error">{{error}}</p>

Routes

Router.js defines the routes and the default template to display, sets up application state, and matches URLs to routes:

[!code-javascriptMain]

   1:  App.Router.map(function () {
   2:      this.route("index", { path: "/" });
   3:      this.route("about");
   4:      this.route("todoList", { path: "/todo" });
   5:  });

TodoListRoute.js loads data for the TodoListRoute by overriding the setupController function:

[!code-javascriptMain]

   1:  App.TodoListRoute = Ember.Route.extend({
   2:      setupController: function (controller, model) {
   3:          controller.set('content', App.TodoList.find());
   4:      }
   5:  });

Ember uses naming conventions to match URLs, route names, controllers, and templates. For more information, see http://emberjs.com/guides/routing/defining-your-routes/ at the EmberJS documentation.

Templates

The Templates folder contains four templates:

The application template acts like a master page. It contains a header, a footer, and an “{{outlet}}” to insert other templates in depending on the route. For more information about application templates in Ember, see http://guides.emberjs.com/v1.10.0/templates/the-application-template//.

The “/todoList” template contains two loop expressions. The outside loop is {{#each controller}}, and the inside loop is {{#each todos}}. The following code shows a built-in Ember.Checkbox view, a customized App.TodoItemEditView, and a link with a deleteTodo action.

[!code-htmlMain]

   1:  {{view Ember.Checkbox checkedBinding="isDone"}}
   2:   
   3:  {{view App.TodoItemEditView valueBinding="title" class="required" disabledBinding="isDone"}}
   4:   
   5:  <a href="#" {{action "deleteTodo" on="click" target="view"}}>X</a>

The HtmlHelperExtensions class, defined in Controllers/HtmlHelperExensions.cs, defines a helper function to cache and insert template files when debug is set to true in the Web.config file. This function is called from the ASP.NET MVC view file defined in Views/Home/App.cshtml:

[!code-cshtmlMain]

   1:  @if (HttpContext.Current.IsDebuggingEnabled)
   2:  {
   3:      @Html.RenderEmber()
   4:  }
   5:  else
   6:  {
   7:      @Scripts.Render("~/bundles/templates")
   8:  }

Called with no arguments, the function renders all of the template files in the Templates folder. You can also specify a subfolder or a specific template file.

When debug is false in Web.config, the application includes the bundle item “~/bundles/templates”. This bundle item is added in BundleConfig.cs, using the Handlebars compiler library:

[!code-csharpMain]

   1:  if (!HttpContext.Current.IsDebuggingEnabled)
   2:  {
   3:      bundles.Add(new Bundle("~/bundles/templates", 
   4:          new EmberHandlebarsBundleTransform()).Include(
   5:              "~/scripts/app/templates/*.hbs"
   6:          ));
   7:  }



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/single-page-application/overview/templates/emberjs-template.htm
< THANKS ME>