Advertisement

Ember.js – another SPA framework

Introduction :   A single-page application (SPA) is a web application that fits on a single web page with the goal of providing a user experience similar to that of a desktop application. In an SPA, either all necessary code – HTML, JavaScript, and CSS – is retrieved with a single page load, or the appropriate resources are dynamically loaded and added to the page as necessary, usually in response to user actions. The page does not reload at any point in the process, nor the control is transferred to another page .Single Page Application allows developers to shift the user interface (UI) and application logic from web servers to the client. The purpose of SPA is rich user experience. This is hard to do with other approaches. Supporting rich interactions with multiple components on a page means that those components have many more intermediate states (e.g. menu open, menu item X selected, menu item Y selected, menu item clicked). Server-side rendering is hard to implement for all the intermediate states - small view states do not map well to URLs. Single page apps are distinguished by their ability to redraw any part of the UI without requiring a server roundtrip to retrieve HTML. This is achieved by separating the data from the presentation of data by having a model layer that handles data and a view layer that reads from the models.

Ember.js History:   Ember.js is a SPA framework, like Angular, Backbone etc. These frameworks reduce the amount of JavaScript the users may have to write otherwise to create SPA. Ember evolved out of a project called SproutCore, created originally in 2007 and used heavily by Apple for various web applications including MobileMe. At emberjs.com, Ember is described as "a JavaScript framework for creating ambitious web applications that eliminates boilerplate and provides standard application architecture." It comes tightly integrated with a template- engine known as Handlebars. As Yehuda Katz, one of Ember's co-founders, is also a member of core team of Rails, Ember is Rails- like - a full-stack opinionated framework that adopts from Rails, the concepts of Convention over Configuration and Don’t Repeat Yourself (DRY).  Yehuda Katz is a member also on TC39, which is the committee responsible for future versions of the JavaScript language. Hence Ember has become an early adopter and pioneer of many standards around JavaScript and the web including promises, web components and ES6 syntax.                                                                                                                                                                      

Tools in Ember: Ember.js is one component of a complete front end stack built and supported by the Ember core team. Other components include

This allows Ember developers to focus on building apps rather than building the support structures that make them run.

2) Ember Data- a client-side data persistence library.

3) Ember Inspector- extensions to web-browsers that make debugging easy.

4) FastBoot- an add-on created by the core-team to run an Ember app on Node.js

5) Liquid Fire - provides animation support for Ember applications.

From third parties, there are thousands of such add-ons that provide various functionalities.

Installation : Getting started with Ember is easy. Ember projects are created and managed through our command line build tool Ember CLI mentioned above. Before the installation of Ember CLI, we must have the Node-Package Manager (NPM) installed. NPM is a package-manager for JavaScript and is installed by default with Node.js. You must install version 0.12 or later of Node.js for Ember CLI to run. You can install Node.js version 5.0.0 or higher, as it will be helpful for your Phoenix installation also. Ember CLI is installed via npm. The tool interprets commands from the user to help create an Ember.js application. Each command from the user is looked up and then executed. Ember CLI relies on several other dependencies including Bower, Lodash ,Broccoli,and Babel, to name a few.

Create a new app:

Execute the following commands:
npm install -g ember-cli@2.10.0

ember new my-app

This  command will create a new directory called my-app and set up a new Ember application inside of it. Out of the box, the application will include everything mentioned earlier under Ember CLI. By providing everything we need to build production-ready web applications in an integrated package, Ember makes starting new projects easy. The generated folders and files include an “app” folder. This is where folders and files for models, components, routes, templates and styles are stored. The majority of our coding on an Ember project happens in this folder.

Change into the application directory my-app and start the development server by typing:

1
2

cd cd my-app
emember server (or ember s ) // to start development server

After a few seconds, we should see the output that looks like this:

Livereload server on http://localhost:49152
Serving on http://localhost:4200/

 (To stop the server at any time, type Ctrl-C in your terminal.)
If we navigate in your Browser to the above address we can see Figure-1.

The default route-handler/router and default template are used. You can have a look at “app/route.js” which contains the default route handler-object that extends ember.Router. You can see the following code in the above file. The anonymous function that maps router to routes is empty.
Router.map(function() {
});

That means only this default-handler will handle the request for root url. [Once you explicitly use generator to add some routes for example ‘books’, you can see the following code added by the tool to the function.

this.route('books');

For each route you add, similar entry will be made in this function]
We will start wring some code.] 

Control –flow in Ember Look at the figure below: The Ember router maps the current URL to one or more route handlers. A route handler can do several things:

The template may or may not use Components for rendering the page.

Defing a Route:

We will explicitly define a route. Ember comes with generators that automate the boilerplate code for common tasks. To generate a route, we have to type this in our terminal:

 
emember generate route books

You'll see output like this:

1
2
3
4
5
6
7

installing route
  create app/routes/books.js //-----1]
  create app/templates/books.hbs  //-----2]
updating router  //---------3]
  add route books
installing route-test
  create tests/unit/routes/books-test.js

 
 
 
 
 
 

 

 

 

 

 

 

 

In other words three new files are created and the existing default-router is updated :

  1.  the route handler.

    2)   the template the route handler will render.
3)  test file.
The application app/router.is updated   adding the “books” router. When we open the router, we can see that the generator has mapped a new books route for us. We can see that  the function passed to Router.map() method, which was earlier empty,   is filled up with the entry  this.route('books'); This entry makes the generated route “books”, the handler for the route “/root URL/books “.                

      Router.map(function() {
  this.route('books');
});

You can see the use of conventions here. The generator generates the route-handler “books.js” under routes folder, makes an entry for the same in the Router.map() method in app/router.js and also generates the relevant template file “books.hbs” under “templates” folder.

   
   
 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Model :  We need some data for the application to be useful. It is the job of the route-handler to supply the data/model to the template which will render the same. In a typical MVC framework it is the responsibility of the Controller. So we can say that Ember is a “MVR” rather than a MVC framework. As our application does not use ember-data – more about this library towards the end of this article-  we don’t require a separate model object. We can use the model() function in Ember.Route class to return the data hard-coded in the route file, as shown below:

/a  app/routes/book.js

Ii           import Ember from 'ember'; 
Le     let books = [{   title: 'Easy Ember',   author: 'Ram' },
{
  T     title: 'Easy JavaScript',
         author: 'Madhan'
},
{
  T    title: 'Easy Rails',
       author: 'Madhan'
},
{
  T  title: 'Easy React',
  A  author: 'Ram'
}];
E    export default Ember.Route.extend({
     model() {
     return books;
        }
});      }); 

 

In a route's model() function, we can return whatever data we want to make available to the template. Hence we have hard coded our data, in the route as the return value of model() hook/function.  The Handlebar expressions in the templates will turn that array of JavaScript objects   into HTML. We can open the books template and add some Handlebars code to loop through the array and print it:

/a app/templates/books.hbs
<   <h2>Book-list</h2>
  {  {{#each model as |book|}}
    Book<br>Title:{{book.title}}<br>
        Author:{{book.author}}<br>

    {{/each}}

Here, we use the each Handle-bar helper to loop over each item in the array we provided from the model() hook and print it .
You can see the browser as in Figure-2.

What are Components?

Web Components are a set of standards that allow for the creation of reusable widgets or components in web documents and web applications. The web component standard aims to create encapsulated, reusable, & generic widgets that abstract UI elements from application code, and deliver a more declarative syntax than other forms of extensions. Components are a major feature of Ember.js. With components, we can encapsulate code and create widgets and custom tags. In addition, we can pass properties to a component, handle events and actions, and  wrap content inside of it. It can take the place of our controller.

Components align closely to the W3C custom elements specification. The W3C specification is still in consideration, and it will probably be adopted by the Web in near future. While the specification has not yet been finalized, it has recently become very popular.

What do Components consist of

In Ember, components currently consist of:

  1. A component template
  2. Javascript backing the component template

The idea is to pass data into a component and based on that data, the component will render a template to the browser.

Creating our component

Components must have at least one dash in their name. So book-list is an acceptable name, but book is not. This prevents clashes with current or future HTML element names and aligns Ember components with the W3C Custom Elements spec. It ensures that Ember detects the components automatically.

Execute
ember generate component book-list
You can see the message:
“installing component.
         Create app\ components\book-list.js
         create app\templates\book-list.hbs ....”

In book-list.js the Ember.component is extended to create a custom component and exported. For a simple application like ours, the generated code need not be touched.

 

/   app/components/book-list.js

}        import Ember from 'ember';

      export  default Ember.Component.extend({
});
);

                   The code that iterates through the Component model has to be given in the component template “book-list.hbs”. The file will read as under:

\a   app\templates\components\book-list.hbs

<    <h2>{{title}}</h2>
{  {{#each books as |book|}}
Book<br>Title:{{book.title}}<br>
Author:{{book.author}}<br>
{{/each}}  

                The file “book.hbs” has to be modified as under:

\a  app\templates\book.hbs

{{      

  {   {{#each model as |book|}}

  {  {{/each}}
{{     {{book-list title="List of Books" books=model}}  ----1]
<   

1]The book-list template has the “books” property. To this property we pass the model -that is the application model that we set up earlier in the router. We have to keep in mind that “books”  is accessed from the inside of the component. The model is used outside the component. The component does not have any access to the model, unless it’s passed to it. This is done in this Handlebars expression.

It is not necessary to modify /routes/books.js and can use it as it is. But we will modify it adding an object to the array to see the difference between the two applications.

If We run the server now, in the browser we can navigate to localhost:4200\books and   see Figure-3.

Ember-data:  We require this library when we want to interact with an external API to get data. It provides many of the facilities of an object-relational mapping (ORM). Ember Data, though a separate library, is included by default when you create a new application, and integrates tightly with Ember to make it easy to retrieve models from your server as JSON, save updates back to the server, and create new models in the browser, without any configuration via a RESTful JSON API that implements the JSON API specification, provided certain conventions are followed.  Thanks to its use of the adapter pattern, Ember Data can also be configured to work with many different kinds of back-ends. There is an entire ecosystem of adapters that allow our Ember app to talk to different types of servers without our writing any networking code. We will see its use in another article.

Conclusion:

Angular.js , React.js and Ember.js are three most popular JavaScript client side frameworks. We have earlier seen Angular-1 Clients for different Restful Web services – JEE, ASP Net MVC, Express.js .It has been completely re-written for version-2, adopting uni-directional data flow and virtual Dom approach as in React. Now the focus is on faster re-rendering .The initial report is that Angular-2 is not backward compatible. React.js is gaining a lot of attention because of its faster re-rendering through a “diffing” algorithm and a uni-directional data-flow. React.js focuses on “V” in MVC, though it can do whatever other MVC frameworks can do, through use of libraries. But it is meant for applications where there are huge and frequent data changes, as its virtual DOM approach can render them fast. Ember is a MVC framework where “C” can stand for either “Controller” or “Component”. In fact Ember documentation calls Controller as a specialized type of Component and they expect to phase out Controller in future. We can write Ember programs with or without writing “C”, as we saw in the first sample above. So it is some- times classified as MVVM (Model View View-Model) framework. Ember-2.js has adopted Glimmer re-rendering engine which uses an algorithm, which is similar to “diffing” in React. It has also adopted the uni-directional data flow from React.js. The advantage/disadvantage of ember.js is that it is a full-stack, opinionated framework like Rails; for this reason it is favoured by many and looked down on by some. The generators for creation of a project and various artefacts are helpful tools and it comes with a development server and a testing framework to make the life of a developer easy. Ember is used on many popular websites, including Discourse, Groupon. Although ember.js is primarily considered a framework for the web, it is also possible to build desktop and mobile applications in Ember. The most notable example of an Ember desktop application is Apple Music, a feature of the iTunes desktop application. With Ember Data, managing models, as our application grows, becomes both simple and easy. For use in a front-end app for back-end data stores or REST apps, now Ember.js is a safer bet, as Ember-data comes in with different adapters. One such adapter is JSON-API adapter which provides a richer domain model with support for collections and relationship between the objects in the collection. The adapters from third parties can also be plugged into it ember-data, if we need. There are also third party libraries which can entirely replace the official library, ember-data, if we want.  This gives Ember a lot of flexibility. We will see it in the Client app for the REST service created with Phoenix in the next article.

localhost:4200\books

Book-list

Book
Title:Easy Ember
Author:Ram
Book
Title:Easy JavaScript
Author:Madhan
Book
Title:Easy Rails
Author:Madhan

Figure 2

  localhost:4200\books

Book-list

Book
Title:Easy Ember
Author:Ram
Book
Title:Easy JavaScript
Author:Madhan
Book
Title:Easy Rails
Author:Madhan
Book
Title:Easy React
Author:Madhan








Added on February 8, 2017 Comment

Comments

#1

Rajeev commented on February 12, 2017 at 5:51 p.m.

The only requirements for Ember is jQuery (not unusual) and Handlebars, which is by the same developer and used for templating. Grunt is used by a great many developers to automate their development workflow. It’s not part of Ember in anyway. Right on the EmberJS.com website homepage is a link to download their files. The starter kit gives you everything you need to get started.

#2

Madhansekaran commented on February 13, 2017 at 5:19 a.m.

The only requirement to bootstrap an ember application now is Node.js/npm to install Ember-CLI, the command-line utily. Other dependencies will be automatically downloaded when a new app is created with Ember-CLI

Post a comment