Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

EmberJS: Exploring the Component framework for Web apps

Ember.js is one of the most famous and used open-source client-side JavaScript application frameworks based on MVC model in the market. In this article well explore most important and productive concepts of this technology.

This article introduces you to the JavaScript framework Ember. Here I will cover the following topics with relevant and simple examples (source code of the examples is attached at the top of the article for your reference, you just need to click at "source code" link):

  • Introduction
  • Concepts
    • Router
    • Views
    • Models
    • Controllers
    • Templates

What is Ember.js

EmberJS is an open source client-side framework for creating rich JavaScript web applications. Ember is used for building long-lived applications. It has a convention that helps writing a better code which can automatically determine the route and the controller name while defining the router resource. Ember.js eliminates the boilerplate (the section of code that has to be included in various places without any alteration) and provides standard application architecture. Ember.js is a two way data-binding, it is also based on Model, Views and Controller (MVC) pattern to maintain front ends. It is designed for Single Page Applications. Ember.js was created by Yehuda Katz andhas HTML and CSS at the core of the development model.

Architecture Diagram of Ember.js

EmberJS Architecture

Figure 1: EmberJS Architecture.

Figure 1 demonstrates the architecture of Ember.js which divides the application into model, view and controller (MVC) which helps the developers quickly understand how everything fits together.

  • Ember starts with route and loads the model. It then renders a template and adds the template to DOM
  • Sets model on controller. Events are passed to the controller to update the model.
  • Later the controller sets the state on template and view.

Model: Model manages the data of the application. It responds to the request from a view and also responds to the instructions from the controller.

Router: Router is used to execute the actions and events; it is an URL representation of application’s objects.

Controller: Controller is an intermediate between the model and view or template. It is auto-generated by Ember.js.

View: View is associated with template, route and controller.

Template: Template is the HTML mark-up; it automatically gets updated whenever model changes. It displays the model to the user.

The following lines should be included while writing the example of Ember.js. They have to be written inside the tag in the html page.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
	<script src="http://cdn.jsdelivr.net/handlebarsjs/1.3.0/handlebars.min.js"></script>
	<script src="http://builds.emberjs.com/release/ember.min.js"></script>
 

Details of the above lines:

  • The first line is used to add the jQuery library.
  • The next line is the handlebar.js library file which is used to power the app’s user interface.
  • The last line is used to add ember.js library, so that it can enable ember code in your page.

Let’s see a simple example of how to use ember. The following simple example shows how to display a message using ember.

Listing 1: HelloWorld.html

<!DOCTYPE html>
<head>
	<title>My first Ember App</title>

	<!-- libraries -->

	<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
	<script src="http://cdn.jsdelivr.net/handlebarsjs/1.3.0/handlebars.min.js"></script>
	<script src="http://builds.emberjs.com/release/ember.min.js"></script>

</head>
<html>
<body>
<script type="text/x-handlebars">
   {{collection App.myCollectionView}}
</script>

<script type="text/x-handlebars" data-template-name="MyView">
  <h1>{{view.content.name}}!</h1>
</script>

		<script type="text/javascript">
			App = Ember.Application.create();

			App.MyView = Ember.View.extend({ templateName: "MyView" });

			App.myCollectionView = Ember.CollectionView.extend({
			    itemViewClass: App.MyView,
			    content: [
			        Ember.Object.create({ name: "Hello World" }),

			    ]
			});

			$(function() { App.initialize(); });
		</script>

</body>
</html>

Details of the code:

  • In the above example, we have shown how a message is displayed using Ember.js
  • Inside the head tag we have included all the library files.
<script type="text/x-handlebars">
{{collection App.myCollectionView}}
</script>

The above code is used to define an application template inside the html code by using tag. Ember will get executed only inside the handlebars script tag. This template will automatically get compiled and display the message on the page when it gets loaded.

<script type="text/x-handlebars" data-template-name="MyView">
  <h1>{{view.content.name}}!</h1>
</script>

In this code the template is defined by using attribute data-template-name="MyView".

  • The App = Ember.Application.create(); line creates the application template.
  • The App.MyView = Ember.View.extend({ templateName: "MyView" }); line indicates the template name called “MyView” .
App.myCollectionView = Ember.CollectionView.extend({
		itemViewClass: App.MyView,
content: [
				Ember.Object.create({ name: "Hello World" }),

			   ]
	});

The Ember object “myCollectionView” extends using data template name “MyView” which uses content to display the specified message by using name attribute.

  • $(function() { App.initialize(); }); line is used to initialize the view.
Execution
  • Save the file as HelloWorld.html .
  • Open this file in the browser, you will see the below output in the browser.
Output of HelloWorld.html

Figure 2: Output of HelloWorld.html

Concepts

Router

Router is used to execute the actions and events; it is an URL representation of application’s objects. The URL is changed manually by the user. The URL is used by ember so that it can understand what application state to be sent or present to the user. The router can link views based on its application state. It is responsible for loading the data and displaying templates.

Logging route changes

Below is a simple code for logging the application transitions from one route to another. It’s possible to see what’s going on in the router when complexity increases in the application.

Below code shows the simple format of logging route changes.

App = Ember.Application.create({
  LOG_TRANSITIONS: true
});

Specifying a root URL

The router can also set the root Url URL when there are multiple web applications running on the same domain.

Below code shows the simple format of specifying a root URL:

	App.Router.reopen({
  	rootURL: '/blog/'
	});

Creation of routes

The URL mapping is invoked by using the map method. The word this is set to create the routes and resources object.

Below code shows the simple format of creatingon the of routes

	App.Router.map(function() {
  		this.route("home", { path: "/home" });
 	 	this.route("contact", { path: "/contact" });
	});
	

Views

Ember views are more convention than they are actual code and are responsible for how and what to display from our application. They don’t contain the HTML markup for the application; they provide idea behind the presentation of the model’s data to the user. Views are used to reflect “how your data model looks like”. It has own DOM element which knows about its model or collection. It handles the user input events and binds the model events and model methods and renders model or collection and interacts with the user.

It represents the logical chunk of UI in the DOM i.e. view classes do not know anything about the HTML and CSS. Each view can be updated independently when model changes without reloading the whole page. Views are used when we want to create a reusable component. It allows defining DOM events declaratively without having to worry about render function to the model into HTML using a template data.

Below code shows the format of how to define view in the program

	var view = Ember.View.create({
		template: Ember.Handlebars.compile(“Whatever you want her”)
	});

Handling Events

Clickable Event:

The below code is a simple clickable event performed where an alert message gets displayed when it’s clicked.

Below code shows the format of clickable events

App. LoggginButton = Ember.View.extend({
  	click: function(c) {
   		 alert("Message displays after the click event!");
 	 }
});

Sending Events:

An event can be something the browser or user does by clicking on button or link.

In below code the views simply by extending the Ember view class performs a click event which affects the application state and send the event to the views controller.

Below code shows the format of sending events

App.LoggginButton = Ember.View.extend({
  	click: function(c) {
    		this.get('controller').send('turnItUp', 11);
  	}
});

This code uses the current controller of the view i.e. LoggedController where the action handler turnItUp is called.

App.LoggedController = Ember.Controller.extend({
			 events:{
			  	turnItUp: function(level){
			    		alert(level);
			 	 }
			}
		});
Example:

Listing 2 shows is a simple example of views that performs a clickable event.

Listing 2: view_example.html

<!DOCTYPE html>
<html>
<head>
	<title>My first Ember App</title>
	<!-- libraries -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/handlebarsjs/1.3.0/handlebars.min.js"></script>
	<script src="http://builds.emberjs.com/release/ember.min.js"></script>
</head>
<body>
<script type="text/x-handlebars" data-template-name="logged">
  <h1> Views Clickable event example</h1>
            {{view.name}}
          {{#view App.LoginButton}}
            <button type="button">Click it</button>
          {{/view}}
</script>

<script type="text/javascript">
	App=Ember.Application.create();
	App.Route= Ember.Route.extend({
	 events: {

		}
	});
App.Router.map(function() {
			    this.resource('logged', {path: '/'});
		});

		App.LoginButton= Ember.View.extend({
			  click: function(c) {
this.get('controller').send('turnItUp', 78);
			  }
		});
		App.LoggedController = Ember.Controller.extend({
			 events:{
			 	turnItUp: function(level){
			   	 alert(level);
			 	 }
			}
		});
</script>
</body>
</html>

Details of the code:

In the above example, we have shown the views click event where after clicking the button the alert message gets displayed.

<script type="text/x-handlebars" data-template-name="logged">
<h1> Views Clickable event example</h1>
            {{view.name}}
          {{#view App.LoginButton}}
            <button type="button">Click it</button>
          {{/view}}
</script>
 

The above code is used to define an application template inside the html code by using tag. Ember will get executed only inside the handlebars script tag. This template will automatically get compiled and result will get display when we click on the button using an alert box. In this code, the template has been defined by the name "logged" by using attribute data-template-name.

App.LoginButton= Ember.View.extend({
			  click: function(c) {
			   this.get('controller').send('turnItUp', 78);
			  }
		});
 

We have created a view simply by extending the Ember view class and performed a click event which affects the application state and send the event to the views controller.

App.LoggedController = Ember.Controller.extend({
			 events:{
			 	 turnItUp: function(level){
			    		alert(level);
			  	}
			}
		});

Here the action handler turnItUp is called. LoggedController is the current controller of the view.

Execution
  • Save this file as view_example.html in your system.
  • Open this file in the browser, you will see the below picture in the browser.
Output of view_example.html

Figure 3: Output of view_example.html .

Models

Model manages the data of the application. It represents the basic data object in the framework. It responds to the request of view and also responds to the instruction from the controller. Model contains a bunch of data and methods for performing related operations and computations on particular data. The Models can respond quickly on the client side to any input to provides the application i.e. keystroke, mouse movements, etc.

Below is a simple code for defining a model:

App.PhoneNumber = DS.Model.extend({
  	number:  DS.attr('string'),
	 Name: DS.attr( 'string' )
});

Here for each and every application it does create a sub-class of DS.Model.

Attach Fixtures to the class:

When developing a client side application we need to put sample data into an application before beginning to develop the application to long term process. The process of adding data to an application can be done by using fixtures.

Below code shows the format of attach fixture to the class

	App.Documenter.reopenClass({
 		 FIXTURES: [
   		 { id: 1, firstName: 'Rushali', lastName: 'Bhatkande' },
   		 { id: 2, firstName: 'Mahantesh' , lastName: 'Nagathan'     }
  		]
	});
	
	

The following lines should be used while writing the Models example. It has to be written inside the tag in the html page.

<script src="http://cdn.bootcss.com/ember-data.js/1.0.0-beta.11/ember-data.js"></script> 

This line should be included after ember.js library.

Example

Listing 3 is a simple example demonstrating Models:

Listing 3: model_example.html

<!DOCTYPE html>
<html>
<head>
	<title>Example using fixture in Model</title>

	<!-- libraries -->
	<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
	<script src="http://cdn.jsdelivr.net/handlebarsjs/1.3.0/handlebars.min.js"></script>
	<script src="http://builds.emberjs.com/release/ember.min.js"></script>
	<script src="http://cdn.bootcss.com/ember-data.js/1.0.0-beta.11/ember-data.js"></script>
</head>

<body>
<script type="text/x-handlebars" data-template-name="index">
    <h2>People:</h2>
    <ul>
        {{#each people}}
        <li>{{name}}</li>
        {{/each}}
    </ul>
    <h2>Colleges:</h2>
      <ul>
      {{#each college}}
          <li>{{name}}</li>
      {{/each}}
    </ul>
</script>
<script type="text/javascript">
	App = Ember.Application.create({});

	App.ApplicationAdapter = DS.FixtureAdapter;

	App.IndexRoute = Ember.Route.extend({
	  model: function() {
	      return Ember.RSVP.hash({
	          people: this.store.find('person'),
	          college: this.store.find('college')
	      })
	  }
	});

	App.Person = DS.Model.extend({
	    name: DS.attr('string')
	});

	App.Person.FIXTURES = [
	    {id: 1, name: 'Atharav'},
	    {id: 2, name: 'Vedant'},
	    {id: 3, name: 'Nilesh'},
	];

	App.College = DS.Model.extend({
	    name: DS.attr('string')
	});

	App.College.FIXTURES = [
	    {id: 1, name: 'Gogte' },
	    {id: 2, name: 'GSS' },
	    {id: 3, name: 'RLS' },
];
</script>
</body>
</html>
 

Details of the code:

  • In the above example we are defining model by using Ember Data Models and have attached fixture to the model.
  • The App.ApplicationAdapter = DS.FixtureAdapter; line instructs Ember.js to use the fixture.
App.IndexRoute = Ember.Route.extend({
		  model: function() {
	     		 return Ember.RSVP.hash({
	          			people: this.store.find('person'),
	          			college: this.store.find('college')
	      		})
	  	}
	});
Here we can edit the article listing route. It customizes the behavior of the route by creating an Ember.Route subclass.
App.Person = DS.Model.extend({
	   	 name: DS.attr('string')
	}); 

For each and every application it creates a sub-class of DS.Model.

  • The App.Person.FIXTURES = [] line is to add data to an application.

Execution

  • Save the file as model_example.html in your system.
  • Just open the file in the browser, and you will see the below picture in the browser.
Output of model_example.html

Figure 4: Output of model_example.html.

Controllers

Controller is an intermediate between the model and view or template. It is auto-generated by Ember.js. In a controller, the templates are been associated depending upon the records., Iif the template is associated with a single model record then it inherits ObjectController, and if it is associated with list of records then it inherits ArrayController. It can have one controller dependent upon another controller as long there is parent/child relationship via URL.

ObjectController

In ObjectController, the template is associated with a single model records. The advantage of using this controller is that it is easy to access the properties of model through ObjectController.

App.PostController = Ember.ObjectController.extend({
	isEditing:null,
	toggleEdit: function(){ this.toggleProperty(‘isEditing’);}
  
});

ArrayController

In ArrayController, the template is associated with a list or multiple models of records. It represents an array of models.

App.PostController=Ember.ArrayController.extends({
itemController: ‘post’
});

Example:

Below is a simple example of Array Controller:

Listing 4: controller_example.html

<!DOCTYPE html>
<html>
<head>
	<title>Array Controller Example</title>

	<!-- libraries -->

	<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
	<script src="http://cdn.jsdelivr.net/handlebarsjs/1.3.0/handlebars.min.js"></script>
	<script src="http://builds.emberjs.com/release/ember.min.js"></script>

</head>
<body>
<script type="text/x-handlebars" data-template-name="index">
  <h2>{{controller.length}}</h2>
  <ul>
    {{#each controller}}
        <li>{{name}}</li>
    {{/each}}
  </ul>
</script>
<script type="text/javascript">
myArray = [Em.Object.create({name: "Mahantesh" }), Em.Object.create({name: "Maruti" }), Em.Object.create({name: "Ganesh" })];
App = Ember.Application.create({});
App.IndexController = Ember.ArrayController.extend({
});

		App.IndexRoute = Ember.Route.extend({
			  setupController: function(controller) {
			    	controller.set('content', myArray);
			}
		});
</script>
</body>
</html>

Details of the code:

  • In the above example, we have shown the array controller example where list of names are displayed.
<script type="text/x-handlebars" data-template-name="index">
<h2>{{controller.length}}</h2>
 	 <ul>
  		 {{#each controller}}
      		<li>{{name}}</li>
    		{{/each}}
  	</ul>
</script>
 

The above code is used to define an application template inside the html code by using tag. Ember will get executed only inside the handlebars script tag. Here, the {{controller.length}} is used to display total number of names present in the list. In this code the template is been defined by the name "index" by using attribute data-template-name.

  • The myArray = [Em.Object.create({name: "Mahantesh" }), Em.Object.create({name: "Maruti" }), Em.Object.create({name: "Ganesh" })]; line is used to create a list of name to be displayed.
App.IndexController = Ember.ArrayController.extend({
});

The above code represents an array of models.

App.IndexRoute = Ember.Route.extend({
		 setupController: function(controller) {
			    controller.set('content', myArray);
}
	});

In route, we have setup IndexController to represent the list of the names.

Execution

  • Save the file as controller_example.html in your system.
  • Just open the file in the browser, you will see the below picture in the browser.
Output of controller_example.html

Figure 5: Output of controller_example.html.

Templates

Template is the HTML mark-up; it automatically gets updated when changes are done in the model. The expression {{property}} inserts information from the model into HTML. It allows templates to be nested by using if and else looping using the {{outlet}} helper. Ember.js uses light weight templating engine known as Handlebars. The template is created inside the html page using the tag. The Ember can use as application template without a template name and it automatically gets appended and compiled to the screen.

The below code shows how to write template in html page:

<script type="text/x-handlebars">
	<div>
    	{{outlet}}
  	</div>
</script>

The property name can be displayed from the controller by using the curly braces.

Conditionals

The outlets allow templates to be nested by using if and else looping using the {{outlet}} helper.

The below code shows how to write template in if and else loop:

{{#if person}}
	{{view HomeView}}  
{{/if}}

if statement is used to conditionally render a block and else statement is used to display an alternate template.

{{#if person}}
  	{{view HomeView}}
             {{else}}
	{{view editAccountView}}
{{/if}}
	

Example:

Below is a simple example of template using if-else loop

Listing 5: templates_example.html

	<!DOCTYPE html>
<html>
<head>
			<title> Simple Example using Templates</title>

		<!-- libraries -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
	<script src="http://cdn.jsdelivr.net/handlebarsjs/1.3.0/handlebars.min.js"></script>
	<script src="http://builds.emberjs.com/release/ember.min.js"></script>

</head>
<style>
.yes{color:#EE82EE;}
.no{color:#DC143C;}
</style>

<body>
<script id="user-template" type="text/x-handlebars-template">
  		 {{#each people}}
   		{{#ifUserInGroup id 2}}
    		 <li>{{first_name}} {{last_name}} <span class="yes">is</span> in the group "Carrom".</li>
   		{{else}}
    	 <li>{{first_name}} {{last_name}} is <span class="no">not</span> in the group "Carrom".</li>
  	 {{/ifUserInGroup}}
 	  {{else}}
  	 <span class="red">list is empty</span>
  		 {{/each}}
  	  </script>
<div id="listOutput"></div>
		<script type="text/javascript">
			Handlebars.registerHelper('ifUserInGroup', function(userId,groupId,options)
			{
			    var containsUser=false;
			        var groups=[{},{id:1,name:'',users:[]},{id:2,name:'chess',users:[1,4]}];
			    if(typeof groups[groupId]!='undefined')
			    for(var i=0;i<groups[groupId].users.length;i++)
			    {
			        if(groups[groupId].users[i]===userId){containsUser=true;break;}
			    }
			  if(containsUser)
			  {
			    return options.fn(this);
			  } else {
			    return options.inverse(this);
			  }
			});
			        var data = {
			            people: [
			              { id:1,first_name: "Mahantesh", last_name: "Nagathan", phone: "9987456321", email: "mahantesh@yahoo.com", member_since: "Jan 14, 2014"},
			              { id:2,first_name: "Maruti", last_name: "Patil", phone: "0987654321", email: "yoyo@gmail.com", member_since: "Dec 19, 2013" },
			              { id:3,first_name: "Ganesh", last_name: "Patil", phone: "9836592272", email: "ganu@gmail.com", member_since: "Nov 25, 2013" },
			              {id:4,first_name: "Naila", last_name: "Kittur", phone: "7284927150", email: "naila@yahoo.com", member_since: "May 21, 2010" },
			              {id:5,first_name: "Rushali", last_name: "Bhatkande", phone: "8263729224", email: "rushali@gmail.com", member_since: "Nov 1, 2013" }
			                    ]
			        };
			        var template = Handlebars.compile($("#user-template").html());
        $('#listOutput').html(template(data));
		</script>

</body>
</html>

Details of the code:

  • In the above example, we have shown the if-else looping method
<script id="user-template" type="text/x-handlebars-template">
   {{#each people}}
   {{#ifUserInGroup id 2}}
     <li>{{first_name}} {{last_name}} <span class="yes">is</span> in the group "Carrom".</li>
   {{else}}
     <li>{{first_name}} {{last_name}} is <span class="no">not</span> in the group "Carrom".</li>
   {{/ifUserInGroup}}
   {{else}}
   <span class="red">list is empty</span>
   {{/each}}
    </script>
 

The above code is used to define an application template inside the html code by using tag. It performs an if-else condition, the condition is true when the person belongs to group, else it is false.

  • The var groups=[{},{id:1,name:'',users:[]} line displays that people doesn’t not belong to the carom group and {id:2,name:'carrom',users:[1,4]}]; line is used the name of the persons who belongs to the carrom group.
for(var i=0;i<groups[groupId].users.length;i++)
 {
if(groups[groupId].users[i]===userId){containsUser=true;break;}
} 

Here we are comparing the id in the group by looping method i.e. using for loop. Initially we are assigning the variable value to zero. Next, we are comparing the user id the assigned value. If both values are equal then it returns true or else false.

  • The var template = Handlebars.compile($("#user-template").html()); line is used to pre-compiled the template and executed with a context in order to return the final HTML fragment.

Execution

  • Save the file as templates_example.html in your system.
  • Just open the file in the browser, and you will see the below picture in the browser.
Output of templates_example.html

Figure 6: Output of templates_example.html.

Conclusion

In this article we discussed about some of the features of Ember.js with some examples. Source code of the examples is attached with this article. As could see, Ember.js is a really powerful framework that can provide to you a better performance and productivity when developing JavaScript web-based applications. For now on, you will have to adapt and increase your knowledge and the best way for this is practicing a lot in Ember and obviously in JavaScript and similar at ll. Hope you liked the article.



I''m a full stack developer with around 10+ yrs of experience. I enjoy writing technical articles on upcoming technical trends.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login