Ember.js Basics

tags:


What is Ember.js?

Ember.js is an open source, free JavaScript client-side framework used for developing web applications. It allows building client side JavaScript applications by providing a complete solution which contains data management and an application flow.

The original name of Ember.js was SproutCore MVC framework. It was developed by Yehuda Katz and initially released on in December 2011. The stable release of Ember.js is 2.10.0 and this was released on November 28, 2016.

Why Ember.js?

Consider the following points to understand the use of Ember.js −

  • Ember.js is an open source JavaScript framework under MIT license.

  • It provides the new binding syntax using the HTMLBars template engine which is a superset of the Handerlbars templating engine.

  • It provides the Glimmer rendering engine to increase the rendering speed.

  • It provides the Command Line Interface utility that integrates Ember patterns into development process and focuses easily on the developer productivity.

  • It supports data binding to create the link between two properties and when one property changes, the other property will get upgraded with the new value.

Features of Ember.js

Following are the some of the most prominent features of Ember.js −

  • Ember.js is used for creating reusable and maintainable JavaScript web applications.

  • Ember.js has HTML and CSS at the core of the development model.

  • It provides the instance initializers.

  • The routes are core features of the Ember.js which are used for managing the URL’s.

  • Ember.js provides Ember Inspector tool for debugging Ember applications.

  • Ember.js uses templates that help to automatically update the model, if the content of applications gets changed.

EmberJS – Installation

It is easy to configure Ember.js in your system. By using the Ember CLI (Command Line Interface) utility, you can create and manage your Ember projects. The Ember CLI deals with different kinds of application asset management such as concatenation, minification and versioning and also provide generators to produce components, routes etc.

To install Ember CLI, you need to have the following dependencies −

  • Git − It is a open source version control system for tracking the changes made in the files. For more information, check the official website of git. Ember uses Git to manage its dependencies.

    • Installing Git on Linux: Install the Git on Linux by using this link – http://git-scm.com/download/linux

    • Installing Git on Mac: Install the Git on Mac OS by using this link – https://git-scm.com/download/mac

    • Installing Git on Linux: Install the Git on Windows by using this link – https://git-scm.com/download/win

  • Node.js and npm − Node.js is an open source, used for developing server side and networking applications. It is written in JavaScript. NPM is a node package manager used for installing, sharing and managing the dependencies in the projects. Ember CLI uses Node.js run time and npm to get the dependencies.

  • Bower − It is used for managing the components such as HTML, CSS, JavaScript, image files etc and can be installed by using the npm.

  • Watchman − This optional dependency can be used to watch the files or directories and execute some actions when they change.

  • PhantomJS − This optional dependency can be used for running browser based unit tests to interact with web page.

Installing Ember CLI

Ember CLI integrates Ember patterns into development process and focuses easily on the developer productivity. It is used for creating Ember apps with Ember.js and Ember data.

You can install Ember using npm as in the command given below −

npm install -g ember-cli

To install the beta version, use the following command −

npm install -g ember-cli@2.10

To check the successful installation of Ember, use the following command −

ember -v

After executing the above command, it will show something like this −

ember-cli: 2.10.1
node: 0.12.7
os: win32 ia32

EmberJS – Core Concepts

Ember.js has the following core concepts −

  • Router
  • Templates
  • Models
  • Components

Emberjs Core Concepts

Router and Route Handlers

The URL loads the app by entering the URL in the address bar and user will click a link within the app. The Ember uses the router to map the URL to a route handler. The router matches the existing URL to the route which is then used for loading data, displaying the templates and setting up an application state.

The Route handler performs the following actions −

  • It provides the template.

  • It defines the model that will be accessible to the template.

  • If there is no permission for the user to visit a particular part of the app, then the router will redirect to a new route.

Templates

Templates are powerful UI for the end-users. Ember template provides user interface look of an application which uses the syntax of Handlebars templates. It builds the front-end application, which is like the regular HTML. It also supports the regular expression and dynamically updates the expression.

Model

The route handlers render the model that persists information to the web server. It manipulates the data stored in the database. The model is the simple class that extends the functionality of the Ember Data. Ember Data is a library that is tightly coupled with Ember.js to manipulate with the data stored in the database.

Components

The component controls the user interface behavior which includes two parts −

  • a template which is written in JavaScript

  • a source file which is written in JavaScript that provides behavior of the components.

EmberJS – Creating and Running Application

You can easily configure the Ember.js in your system. The installation of Ember.js is explained in the EmberJS Installation chapter.

Creating Application

Let us create one simple app using Ember.js. First create one folder where you create your applications. For instance, if you have created the “emberjs-app” folder, then navigate to this folder as −

$ cd ~/emberjs-app

Inside the “emberjs=app” folder, create a new project by using the new command −

$ ember new demo-app

When you create a project, new command provides the following directory structure with files and directories −

|-- app
|-- bower_components
|-- config
|-- dist
|-- node_modules
|-- public
|-- tests
|-- tmp
|-- vendor

bower.json
ember-cli-build.js
package.json
README.md
testem.js
  • app − It specifies the folders and files of models, routes, components, templates and styles.

  • bower_components / bower.json − It is used for managing the components such as HTML, CSS, JavaScript, image files etc and can be installed by using the npm. The bower_components directory contains all the Bower components and bower.json contains the list of dependencies which are installed by Ember, Ember CLI Shims and QUnit.

  • config − It contains the environment.js directory which is used for configuring the settings of an application.

  • dist − It includes the output files which are deployed when building the app.

  • node_modules / package.json − NPM is a node package manager for Node.js which is used for installing, sharing and managing the dependencies in the projects. The package.json file includes the current npm dependencies of an application and the listed packages get installed in the node_modules directory.

  • public − It includes assets like images, fonts, etc.

  • vendor − It is a directory in which the front-end dependencies such as JavaScript, CSS are not controlled by Bower go.

  • tests / testem.js − The automated tests are stored under the tests folder and the test runner testem of Ember CLI’s is arranged in testem.js.

  • tmp − It contains the temporary files of Ember CLI.

  • ember-cli-build.js − It specifies how to build the app by using the Ember CLI.

Running Application

To run the application, navigate to the newly created project directory −

$ cd demo-app

We have created the new project and it is ready to run with the command given below −

$ ember server

Now open the browser and navigate to http://localhost:4200/. You will get the Ember Welcome page as shown in the image below −

Ember.js App Example

EmberJS – Object Model

In Ember.js, all objects are derived from the Ember.Object. Object-oriented analysis and design technique is called object modeling. The Ember.Object supports features such as mixins and constructor methods by using the class system. Ember uses the Ember.Enumerable interface to extend the JavaScript Array prototype to give the observation changes for arrays and also uses the formatting and localization methods to extend the String prototype.

The following table lists down the different types of object model in Ember.js along with their description −

S.No. Types & Description
1 Classes and Instances

Class is a template or blue print, that has a collection of variables and functions, whereas instances are related to the object of that class. You can create new Ember class by using the Ember.Object’s extend() method.

2 Reopening Classes and Instances

This is nothing but updating the class implementation without redefining it.

3 Computed Properties

A computed property declares functions as properties and Ember.js automatically calls the computed properties when needed and combines one or more properties in one variable.

4 Computed Properties and Aggregate Data

The computed property accesses all items in an array to determine its value.

5 Observers

The observer observes the property such as computed properties and updates the text of the computed property.

6 Bindings

The binding is a powerful feature of Ember.js which helps to create a link between two properties and if one of the properties gets changed, the other one is updated automatically.

EmberJS – Router

Router is a core feature of EmberJs which translates an URL into a series of templates and represents the state of an application.The Ember uses the router to map the URL to a route handler. The router matches the current URL to other routes which are used for loading data, displaying the templates and to set up an application state.

Route handler performs some actions such as −

  • It provides the template.

  • It defines the model and it will be accessible to the template.

  • If there is no permission for user to visit the particular part of an app, then router will redirect to a new route.

The following table lists down the different routers in Ember.js along with their description −

S.No. Types & Description
1 Defining Routes

The router matches the current URL with routes responsible for displaying template, loading data and setting up an application state.

2 Specifying a Route’s Model

To specify a routes model, you need a template to display the data from the model.

3 Rendering a Template

The routes are used to render the external template to the screen.

4 Redirecting

It is a URL redirection mechanism that redirects the user to a different page when the requested URL is not found.

5 Preventing and Retrying Transitions

The transition.abort() and transition.retry() methods can be used to abort and retry the transition respectively during a route transition.

6 Loading/Error Substates

Ember router provides information of a route loading and errors which occur when loading a route.

7 Query Parameters

Query parameters come into view at the right side of the “?” mark in a URL represented as optional key-value pairs.

8 Asynchronous Routing

Ember.js router has the ability to handle complex async logic within an application by using asynchronous routing.

EmberJS – Templates

A template is used to create a standard layout across multiple pages. When you change a template, the pages that are based on that template automatically get changed. Templates provide standardization controls.

The below table shows some more details about templates −

S.No. Types & Description
1 Handlebars Basics

The Handlebars templating library allows building rich user interface by including static HTML and dynamic content.

2 Built-in Helpers

Helpers provide extra functionality to the templates and modifies the raw value from models and components into proper format for users.

3 Conditionals

Ember.js defines the two conditional statements which help to control the flow of program.

4 Displaying List of Items

You can display the list of items in an array by using the #each helper.

5 Displaying Keys in an Object

You can display the keys in the object by using the #each-in helper.

6 Links

The {{link-to}} component can be used to create a link to a route.

7 Actions

The HTML element can be made clickable by using the {{action}} helper.

8 Input Helpers

The common form controls can be created by using the {{input}} and {{textarea}} helpers in the Ember.js

9 Development Helpers

The template developement can be made easier by using some helpers of Handlebars and Ember.

10 Writing Helpers

You can add extra functionality to the templates and converts the raw values from models and components into proper format for the users.

EmberJS – Components

The Ember.js components uses the W3C web component specification and provides true encapsulation UI widgets. It contains the three main specification as templates, shadow DOM and custom elements. The component is declared within the data-template-name which has a path name instead of a plain string and are prefixed with “components/”.

The following table lists down the action events of actions −

S.No. Action Events & Description
1 Defining a Component

You can easily define a component in Ember.js and each component must have a dash in their name.

2 Component Lifecycle

Component lifecycle uses some of the methods in order to execute the code at specific times in a component’s life.

3 Passing Properties to a Component

The component doesn’t access the property directly in the template scope. Therefore, just declare the property at the time of component deceleration.

4 Wrapping Content in a Component

You can wrap the content in a component by using the templates.

5 Customizing a Component’s Element

You can customize the component’s element such as attributes, class names by using a subclass of Ember.Component in the JavaScript.

6 Using Block Params

The passed properties in a component can give back the result in a block expression.

7 Handling Events

The user events such as double-click, hovering, key press etc can be handled by event handlers. To do this, apply the event name as a method on the component.

8 Triggering Changes with Actions

Components can trigger the changes and communicate with events by using the actions.

EmberJS – Models

Model is a class that extends the functionality of the Ember Data. When a user refreshes the page, the contents of page should be represented by a model. In Ember.js, every route has an associated model. The model helps to improve the performance of application. The Ember Data manipulates the stored data in the server and also works easily with streaming APIs like socket.io and Firebase or WebSockets.

Core Concepts

  • Store
  • Models
  • Records
  • Adapter
  • Caching

Store

The store is a central repository and cache of all records available in an application. The route and controllers can access the stored data of your application. The DS.Store is created automatically to share the data among the entire object.

import Ember from 'ember';

export default Ember.Route.extend ({
   model() {
      return this.store.find();
   }
});

Models

Model is a class that extends the functionality of the Ember Data, which specifies relationships with other objects. When a user refreshes the page, the contents of page should be represented by a model.

import DS from 'ember-data';

export default DS.Model.extend ({
   owner: DS.attr(),
   city: DS.attr()
});

Records

A record is an instance of a model that includes the information, which is loaded from a server and you can identify the record by its model type and ID.

//It finds the record of type 'person' and an 'ID' of 1
this.get('store').findRecord('person', 1); // => { id: 1, name: 'steve-buscemi' }

Adapter

An adapter is an object that is responsible for translating requested records from Ember into appropriate calls to particular server backend. For instance, if you want to find a person with ID of 1, then Ember will load the URL by using HTTP as /person/1.

Caching

The records can be cached automatically by the store and returns the same object instance when you load the records from the server for the second time. This improves the performance of your application and displays the application UI to the user as fast as possible.

The following table lists down the details about models −

S.No. Model Ways & Description
1 Defining Models

Model is a simple class that extends the functionality of the Ember Data.

2 Finding Records

You can retrieve the records by using the Ember data store.

3 Creating and Deleting Records

You can create and delete the records on the instance of model.

4 Relationships

Ember.js provides relationship types to specify how the models are related to each other.

5 Pushing Records Into The Store

You can push the records into the store’s cache without requesting the records from an application.

6 Handling Metadata

Metadata is a data that is used for specific model or type instead of using record.

7 Customizing Adapters

Ember.js Adapter specifies how data is kept on at the backend data store such as URL format and REST API headers.

EmberJS – Managing Dependencies

Ember uses NPM and Bower for managing dependencies which are defined in package.json for NPM and bower.json for Bower. For instance, you may require installing SASS for your style sheets which is not installed by Ember while developing Ember app. To accomplish this, use the Ember Addons for sharing the reusable libraries. If you want to install any CSS framework or JavaScript datepicker dependencies, then use the Bower package manager.

Addons

The Ember CLI can be used to install the Ember Addons by using the following command −

ember install ember-cli-sass

The ember install command will save all the dependencies to the respective configuration file.

Bower

It is a package manager for the web which manages the components of HTML, CSS, JavaScript or image files. It basically maintains and monitors all packages and examines new updates. It uses the configuration file bower.json to keep track of applications placed at the root of the Ember CLI project.

You can install the project dependencies by using the following command −

bower install <dependencies> --save

Assets

You can place the third-party JavaScript in the vendor/ folder of your project which are not available as an Addon or Bower package and place the own assets such as robots.txt, favicon, etc. in the public/ folder of your project. The dependencies which are not installed by Ember while developing the Ember app, should be included by using the manifest file ember-cli-build.js.

AMD JavaScript modules

You can give the asset path as the first argument and the list of modules and exports as the second argument. You can include these assets in the ember-cli-build.js manifest file as −

app.import('bower_components/ic-ajax/dist/named-amd/main.js', {
   exports: {
      'ic-ajax': [
         'default',
         'defineFixture',
         'lookupFixture',
         'raw',
         'request'
      ]
   }
});

Environment Specific Assets

The different assets can be used in different environments by defining object as first parameter which is an environment name and the value of an object should be used as asset in that environment. In the ember-cli-build.js manifest file, you can include as −

app.import ({
   development: 'bower_components/ember/ember.js',
   production:  'bower_components/ember/ember.prod.js'
});

Other Assets

Once all the assets are placed in the public/ folder, they will get copied into the dist/ directory. For instance, if you copy a favicon placed at the public/images/favicon.ico folder, this will get copied into the dist/images/favicon.ico directory. The third-party assets can be added manually in the vendor/ folder or by using the Bower package manager via the import() option. The assets which are not added by using the import() option, will not be present in the final build.

For instance, consider the following line of code which imports the assets into the dist/ folder.

app.import('bower_components/font-awesome/fonts/fontawesome-webfont.ttf');

The above line of code creates a font file in dist/font-awesome/fonts/fontawesomewebfont.ttf. You can also place the above file at a different path as shown below −

app.import('bower_components/font-awesome/fonts/fontawesome-webfont.ttf', {
   destDir: 'assets'
});

It will copy the font file in dist/assets/fontawesome-webfont.ttf.

EmberJS – Application Concerns

The Ember application can be extended by using the Ember.Application class which declares and configures the objects that are helpful in building your application.

Application creates the Ember.ApplicationInstance class while running which is used for managing its aspects and it acts as owner for instantiated objects. In short, the Ember.Application class defines the application and the Ember.ApplicationInstance class manages its state.

The following table lists down more details about models −

S.No. Model Ways & Description
1 Dependency Injection

It is a process of supplying dependencies of one object to another and used by an Ember application to declare and instantiates the objects and dependencies classes between them.

2 Initializers

Initializers are used to configure an application as it boots.

3 Services

Service is an Ember object which can be made available in the different parts of the application.

4 The Run Loop

It is a region where most of the application’s internal code takes place.

EmberJS – Configuring Ember.js

The Ember.js can be configured for managing the application’s environment. The configuring Ember.js includes the following topics −

S.No. Configuring Ways & Description
1 Configuring App and Ember CLI

You can configure the Ember App and CLI for managing the application’s environment.

2 Disabling Prototype Extensions and Specifying URL Type

The prototype extensions can be disabled by setting the EXTEND_PROTOTYPES flag to false and specifying the URL type by using the Ember router options.

3 Embedding Applications and Feature Flags

You can Embed an application into an existing page by changing the root element and feature flags can be enabled based on the project’s configuration.

EmberJS – Ember Inspector

Ember inspector is a browser add-on which is used to debug the Ember applications. The Ember inspector includes the following topics −

S.No. Ember inspector Ways & Description
1 Installing the Inspector

You can install the Ember inspector to debug your application.

2 Object Inspector

The Ember inspector allows interacting with the Ember objects.

3 The View Tree

The view tree provides the current state of an application.

4 Inspecting Routes, Data Tab and Library Info

You can see the list of application’s routes defined by the inspector and the Data tab is used to display the list of model types.

5 Debugging Promises

Ember inspector provides promises based on their states.

6 Inspecting Objects and Rendering Performance

Use the Container for inspecting the object instances and compute the application’s render time by using the Render Performance option.