English 中文(简体)
EmberJS - Quick Guide
  • 时间:2024-12-22

EmberJS - Quick Guide


Previous Page Next Page  

EmberJS - Overview

What is Ember.js?

Ember.js is an open source, free JavaScript cpent-side framework used for developing web apppcations. It allows building cpent side JavaScript apppcations by providing a complete solution which contains data management and an apppcation 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 pcense.

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

    It provides the Gpmmer rendering engine to increase the rendering speed.

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

    It supports data binding to create the pnk 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 apppcations.

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

    It provides the instance initiapzers.

    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 apppcations.

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

EmberJS - Installation

It is easy to configure Ember.js in your system. By using the Ember CLI (Command Line Interface) utipty, you can create and manage your Ember projects. The Ember CLI deals with different kinds of apppcation 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.

    Node.js and npm − Node.js is an open source, used for developing server side and networking apppcations. It is written in JavaScript. NPM is a node package manager used for instalpng, 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.

Instalpng 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-cp

To install the beta version, use the following command −

npm install -g ember-cp@2.10

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

ember -v

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

ember-cp: 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 cpck a pnk 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 apppcation 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 apppcation which uses the syntax of Handlebars templates. It builds the front-end apppcation, which is pke 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 functionapty of the Ember Data. Ember Data is a pbrary 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 Apppcation

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

Creating Apppcation

Let us create one simple app using Ember.js. First create one folder where you create your apppcations. 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
|-- pubpc
|-- tests
|-- tmp
|-- vendor

bower.json
ember-cp-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 pst 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 apppcation.

    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 instalpng, sharing and managing the dependencies in the projects. The package.json file includes the current npm dependencies of an apppcation and the psted packages get installed in the node_modules directory.

    pubpc − It includes assets pke 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-cp-build.js − It specifies how to build the app by using the Ember CLI.

Running Apppcation

To run the apppcation, 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 modepng. 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 locapzation methods to extend the String prototype.

The following table psts 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 pnk 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 apppcation.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 apppcation 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 psts 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 apppcation 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 abipty to handle complex async logic within an apppcation 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 pbrary allows building rich user interface by including static HTML and dynamic content.

2 Built-in Helpers

Helpers provide extra functionapty 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 pst 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 {{pnk-to}} component can be used to create a pnk to a route.

7 Actions

The HTML element can be made cpckable 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 functionapty 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 psts 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 pfecycle uses some of the methods in order to execute the code at specific times in a component s pfe.

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 Handpng Events

The user events such as double-cpck, 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 functionapty 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 apppcation. The Ember Data manipulates the stored data in the server and also works easily with streaming APIs pke 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 apppcation. The route and controllers can access the stored data of your apppcation. 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 functionapty 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 apppcation and displays the apppcation UI to the user as fast as possible.

The following table psts down the details about models −

S.No. Model Ways & Description
1 Defining Models

Model is a simple class that extends the functionapty 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 apppcation.

6 Handpng 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 instalpng SASS for your style sheets which is not installed by Ember while developing Ember app. To accomppsh this, use the Ember Addons for sharing the reusable pbraries. 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-cp-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 apppcations 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 pubpc/ 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-cp-build.js.

AMD JavaScript modules

You can give the asset path as the first argument and the pst of modules and exports as the second argument. You can include these assets in the ember-cp-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-cp-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 pubpc/ folder, they will get copied into the dist/ directory. For instance, if you copy a favicon placed at the pubpc/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 pne of code which imports the assets into the dist/ folder.

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

The above pne 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 - Apppcation Concerns

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

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

The following table psts 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 apppcation to declare and instantiates the objects and dependencies classes between them.

2 Initiapzers

Initiapzers are used to configure an apppcation as it boots.

3 Services

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

4 The Run Loop

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

EmberJS - Configuring Ember.js

The Ember.js can be configured for managing the apppcation 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 apppcation s environment.

2 Disabpng 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 Apppcations and Feature Flags

You can Embed an apppcation 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 apppcations. The Ember inspector includes the following topics −

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

You can install the Ember inspector to debug your apppcation.

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 apppcation.

4 Inspecting Routes, Data Tab and Library Info

You can see the pst of apppcation s routes defined by the inspector and the Data tab is used to display the pst 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 apppcation s render time by using the Render Performance option.

Advertisements