Ember Js
Ember Js
js
#ember.js
Table of Contents
About 1
Remarks 2
Versions 2
Up-To-Date Release 2
Examples 2
Installation or Setup 2
Dependencies 2
Git 3
Watchman (optional) 3
PhantomJS (optional) 3
Installation 3
Creating App 3
Deploy App 4
Assign localhost ports (esp. permissions/availability issues, running multiple ember sites 4
Remarks 6
Examples 6
ember-concurrency task 6
Pros 6
Cons 6
JavaScript 6
Template 7
PromiseProxyMixin 7
Pros 7
Cons 7
JavaScript 7
Template 8
Chapter 3: Component - communication between child to parent component. 9
Syntax 9
Remarks 9
Examples 9
Composable Components 9
Remarks 11
Examples 11
Examples 12
Chapter 6: Debugging 14
Examples 14
Logging EmberData 14
Introduction 16
Syntax 16
Examples 16
Remarks 18
Examples 18
Updating Ember 18
Introduction 20
Parameters 20
Remarks 20
Examples 21
Introduction 23
Examples 23
Credits 24
About
You can share this PDF with anyone you feel could benefit from it, downloaded the latest version
from: ember-js
It is an unofficial and free ember.js ebook created for educational purposes. All the content is
extracted from Stack Overflow Documentation, which is written by many hardworking individuals at
Stack Overflow. It is neither affiliated with Stack Overflow nor official ember.js.
The content is released under Creative Commons BY-SA, and the list of contributors to each
chapter are provided in the credits section at the end of this book. Images may be copyright of
their respective owners unless otherwise specified. All trademarks and registered trademarks are
the property of their respective company owners.
Use the content presented in this book at your own risk; it is not guaranteed to be correct nor
accurate, please send your feedback and corrections to [email protected]
https://riptutorial.com/ 1
Chapter 1: Getting started with ember.js
Remarks
This section provides an overview of what ember.js is, and why a developer might want to use it.
It should also mention any large subjects within ember.js, and link out to the related topics. Since
the Documentation for ember.js is new, you may need to create initial versions of those related
topics.
Versions
Up-To-Date Release
2.13.0 2017-04-29
Examples
Installation or Setup
Getting started with Ember is easy. Ember projects are created and managed through our
command line build tool Ember CLI. This tool provides:
Dependencies
Node.js and npm
Ember CLI is built with JavaScript, and expects the Node.js runtime. It also requires dependencies
fetched via npm. npm is packaged with Node.js, so if your computer has Node.js installed you are
ready to go.
https://riptutorial.com/ 2
Ember requires Node.js 0.12 or higher and npm 2.7 or higher. If you're not sure whether you have
Node.js or the right version, run this on your command line:
node --version
npm --version
If you get a "command not found" error or an outdated version for Node:
• Windows or Mac users can download and run this Node.js installer.
• Mac users often prefer to install Node using Homebrew. After installing Homebrew, run brew
install node to install Node.js.
• Linux users can use this guide for Node.js installation on Linux.
Git
Ember requires Git to manage many of its dependencies. Git comes with Mac OS X and most
Linux distributions. Windows users can download and run this Git installer.
Watchman (optional)
On Mac and Linux, you can improve file watching performance by installing Watchman.
PhantomJS (optional)
You can run your tests from the command line with PhantomJS, without the need for a browser to
be open. Consult the PhantomJS download instructions.
Installation
Install Ember using npm:
ember -v
Creating App
Ember CLI allows you to use one of two options to generate a new app:
1. Create a folder and run ember init (generates application structure and sets up git and
makes your first commit)
https://riptutorial.com/ 3
2. Run ember new <app name> (creates a folder with the specified name, steps into it and runs
ember init)
Once the generation process is complete, boot a live-reload server within the app folder by
running:
ember server
or ember s for short. *Ta-da, now you have a running Ember app! Official Docs
The application template is always on screen when a user is visiting your application. In your
editor of choice, open app/templates/application.hbs and add the following code:
{{outlet}}
Now you should see the newly added text on the welcome page of your application. Also notice
that Ember automatically detects the new file and reloads the page for you. Neat, right?
Deploy App
To deploy an Ember application simply transfer the output from ember build to a web server. This
can be done with standard Unix file transfer tools such as rsync or scp. There are also services that
will let you deploy easily.
ember build
scp -r dist/* myserver.com:/var/www/public/
normally we would use ember build --environment=production which does more to make your code
ready for production (gzip and minify code).
1. Ember add-on
2. Import JavaScript plugins globally
3. Consume named AMD plugins
4. Via ember-browserify
https://riptutorial.com/ 4
ember sites simultaneously)
Occasionally it's useful to assign one or more ports manually vs using the defaults. Doing so can
solve port availability/permissions issues or accommodate running more than one ember instance
at a time.
Per ember help: "Pass 0 to automatically pick an available port". (In a terminal, type ember help).
To run more than one ember site at the same time, each needs its own server and live-reload
ports. A simple approach: in separate Terminal windows navigate to each instance and use the
following to launch them with their own ports:
If you get an error about availability or permission in any of these cases, enter the following python
script at your Terminal prompt to identify an available port:
https://riptutorial.com/ 5
Chapter 2: Asynchronous Tasks in
Components
Remarks
in ember-concurrency the extra setting of error is a work around to prevent thrown exceptions from
bubbling up to Ember's onerror (since it is meant to be handled in the template). There is a feature
request to handle this better.
Examples
ember-concurrency task
Pros
• Intuitive reasoning of complex asynchronous code.
• Offers a complete API for managing tasks.
• Can be canceled.
• Can be used directly in a component without the need of a proxy object.
• Destructures promises inside the task function.
• Can use JavaScript try / catch / finally blocks to manage asynchronous assignment,
exceptions, and cleanup.
• Tasks are automagically cancelled on willDestroy event, avoiding errors setting values on
destroyed objects (e.g. after a timer)
Cons
• Not builtin – requires ember install ember-concurrency
• Uses generator functions that can confuse developers used to promise chains.
JavaScript
https://riptutorial.com/ 6
myTask: task(function * () {
set(this, 'error', null);
try {
yield timeout(2000);
return 'Foobar';
} catch (err) {
set(this, 'error', error);
}
}).keepLatest()
});
Template
{{#if myTask.isIdle}}
<button onclick={{perform myTask}}>
Start Task
</button>
{{else}}
Loading…
{{/if}}
{{#if myTask.last.value}}
Done. {{myTask.last.value}}
{{/if}}
{{#if error}}
Something went wrong. {{error}}
{{/if}}
PromiseProxyMixin
Ember comes with a built in helper that will provide computed properties for the status of an
asynchronous task.
Pros
• Built in – no need for an addon.
• Can be managed in the life cycle of a component.
• Provides convenient state properties that can drive the template logic.
Cons
• Must be wrapped in an Ember.Object and cannot be applied to an Ember.Component directly.
• Creates a disconnect between the original promise chain and the destructing of the content
value.
• Is not very intuitive and can be difficult to reason with.
• Cannot be cancelled.
JavaScript
https://riptutorial.com/ 7
import Ember from 'ember';
const {
Component, PromiseProxyMixin, get, set, computed,
isPresent, run, RSVP: { Promise }
} = Ember;
actions: {
performTask() {
const fakeTask = new Promise((resolve) => {
run.later(resolve, 'Foobar', 2000);
});
set(this, 'promise', fakeTask);
}
}
});
Template
{{#if myProxy.isPending}}
Loading…
{{else}}
<button onclick={{action "performTask"}}>
Start Task
</button>
{{/if}}
{{#if myProxy.isFulfilled}}
Done. {{myProxy.content}}
{{/if}}
{{#if myProxy.isRejected}}
Something went wrong. {{myProxy.reason}}
{{/if}}
https://riptutorial.com/ 8
Chapter 3: Component - communication
between child to parent component.
Syntax
• (yield-- Allows you to export items from a component
• (hash -- Allows you to export a hash or object, since this is required to call child components
within the parent's block. The requirement is that there is a . for the component to be created
• (component -- Creates the child component which can take anything in the parent's context.
The component can be curried, since it is only called when the user uses it, so add as many
attributes as you need, and the user can add the rest.
• (action -- Creates an action based on a function or a string pointing to a function in the
actions hash of the parent component in this case.
Remarks
For creating components that interact with a parent component, composable components are the
best option, although they require Ember 2.3+.
Examples
Composable Components
Inside parent-component.hbs
{{yield (hash
child=(
component 'child-component'
onaction=(action 'parentAction')
)
)}}
Inside parent-component.js
Inside child-component.js
https://riptutorial.com/ 9
// On click we call the action passed down to us from the parent
click() {
let data = this.get('data');
this.get('onaction')(data);
}
});
Inside usage.hbs
{{#parent-component as |ui|}}
{{#each model as |item|}}
{{ui.child data=item}}
{{/each}}
{{/parent-component}}
https://riptutorial.com/ 10
Chapter 4: Currency formatting template
helper
Remarks
More details available in Ember guides, where this example was taken from.
Compatible with Ember 2.2.0+ (2.11.0 was the latest at the time of writing)
Examples
Creating a new helper
https://riptutorial.com/ 11
Chapter 5: Date Format Helper
Examples
Helper for a clean date and hour format.
When you want the current date and time, you can do this with the Javascript function Date, but will
return the following format which isn't always useful: Wed Jun 07 2017 13:26:15 GMT+0200 (Romance
(zomertijd)).
Copy the following code into app/helpers/helpers.js, and simply call getCurrentDateAndFormat()
instead of new Date().
if (dd<10) {
dd= '0'+dd;
}
if (MM<10) {
MM= '0'+MM;
}
if (hh<10) {
hh= '0'+hh;
}
if (mm<10) {
mm= '0'+mm;
}
return today;
}
The helper extracts all separate time values, adds a 0 if the value is below 10 (for format and
readability) and reassembles them in a more fitting format. In this case: day, month, year, hours
and minutes.
https://riptutorial.com/ 12
will display: 06/07/2017 13h26
Changing month and date position, depending on your region, is as easy as replacing MM with dd
and vice versa, as evident from above example.
https://riptutorial.com/ 13
Chapter 6: Debugging
Examples
Logging EmberData
The ember data models have a toJSON method that extracts the relevant data:
console.log(model.toJSON());
If you want to log the data in a more app-specific way, you can use serialize:
model.serialize();
which uses the serialization strategy you can define in the store's adapter to create a JSON
representation of the model.
All objects in an Ember app, including Ember Data models, inherit from Ember.CoreObject, which
has a toString method that prints this representation:
<app-name@ember-type:object-name:id>
Explanation:
You can overwrite this value using the method toStringExtension in your particular model.
For comparison example, here's how logging an application controller could look:
<my-awesome-app@controller:application::ember324>
Ember has a static global method called runInDebug which can run a function meant for
debugging.
Ember.runInDebug(() => {
// this code only runs in dev mode
});
https://riptutorial.com/ 14
In a production build, this method is defined as an empty function (NOP). Uses of this method in
Ember itself are stripped from the ember.prod.js build.
https://riptutorial.com/ 15
Chapter 7: How to import JavaScript
library/plugin
Introduction
Open the directory of your ember.js project, You will find there a file named ember-cli-build.js. You
can install Your libraries or plugins using bower, then point the import to the bower_components
folder, but if you have a file You want to add, just drag them to the folder of Your project and write
the app.import to that file.
Syntax
• app.import('path to file starting from project folder/file.js');
Examples
Example ember-cli-build.js file
module.exports = function(defaults) {
var app = new EmberApp(defaults, {
// Add options here
datatables: {
core: true,
style: 'bs',
extensions: [
{ name: 'buttons', extensions: ['colVis','flash','html5','print'] },
{ name: 'responsive', style: 'bs' },
'select'
],
pdfmake: false,
vfs_fonts: false,
jszip: true
}
});
//Imports:
app.import('bower_components/js-cookie/src/js.cookie.js');
app.import('bower_components/moment/min/moment.min.js');
app.import('bower_components/crypto-js/crypto-js.js');
// Use `app.import` to add additional libraries to the generated
// output files.
//
// If you need to use different assets in different
// environments, specify an object as the first parameter. That
// object's keys should be the environment name and the values
// should be the asset to use in that environment.
//
// If the library that you are including contains AMD or ES6
// modules that you would like to import into your application
https://riptutorial.com/ 16
// please specify an object with the list of modules as keys
// along with the exports of each module as its value.
return app.toTree();
};
https://riptutorial.com/ 17
Chapter 8: How to update Ember, Ember Data
and Ember CLI
Remarks
• To find the latest stable version of Ember, click here.
• To find the latest stable version of Ember Data, click here.
• To find the latest stable version of Ember CLI, click here.
Examples
Updating Ember
In this example, 2.13.2 is the latest version. We install it via bower, specifying the particular version
as ember#2.13.2 and including the save flag to persist it to bower.json.
As of writing this post the latest version is 2.13.2. From the command line, in the root of your app's
directory, run:
You may be prompted to choose your version of Ember. If you are, prepend your answer with a !
to make sure it's saved.
Since Ember Data is an Ember CLI add-on we can install it just like any other add-on by using
ember install.
As of writing this post the latest version is 2.13.1. From the command line, in the root of your app's
directory, run:
Ember CLI is a normal npm package. To update it we have to uninstall it and then install the
version we want.
As of writing this post the latest version is 2.13.2. From the command line run:
https://riptutorial.com/ 18
npm cache clean
bower cache clean
npm install -g [email protected]
ember -v
Then update your project. This will clear out the cache and update the Ember CLI version in
package.json. The last part will run the new project blueprint on your projects directory. Just follow
the prompts and review all the changes.
references
Read How to update Ember, Ember Data and Ember CLI online: https://riptutorial.com/ember-
js/topic/1722/how-to-update-ember--ember-data-and-ember-cli
https://riptutorial.com/ 19
Chapter 9: Initialize Foundation or Bootstrap
on ember-cli in a proper way
Introduction
Bootstrap : I think that's not proper way. The best way in my opinion is an ember-bootstrap addon.
ember-bootstrap uses the Bootstrap CSS classes while replacing the behaviors from the
components Bootstrap implements in bootstrap.js, such as toggle, navbar, modal, etc., with
equivalent, CSS class-compatible native Ember components.
Foundation: There is an addon called Ember CLI Foundation 6 SASS, it's also installed using
command line.
Parameters
Parameter Usage
Remarks
Both addons are not mine, I thought it will be nice to present them to You, there are github pages
of addons:
https://riptutorial.com/ 20
Examples
Install ember-bootstrap with default version
ember g ember-cli-foundation-6-sass
// ember-cli-build.js
module.exports = function(defaults) {
var app = new EmberApp(defaults, {
// Add options here
'ember-cli-foundation-6-sass': {
'foundationJs': [
'core',
'util.box',
'util.keyboard',
'util.mediaQuery',
'util.motion',
'util.nest',
'util.timerAndImageLoader',
'util.touch',
'util.triggers',
'abide',
'accordion',
'accordionMenu',
'drilldown',
'dropdown',
'dropdownMenu',
'equalizer',
'interchange',
'magellan',
'offcanvas',
'orbit',
https://riptutorial.com/ 21
'responsiveMenu',
'responsiveToggle',
'reveal',
'slider',
'sticky',
'tabs',
'toggler',
'tooltip'
]
},
}
});
return app.toTree();
};
https://riptutorial.com/ 22
Chapter 10: Testing
Introduction
Creating and maintaining a comprehensive test suite should be a priority for each developer.
Testing in Ember.js involves dealing with asynchrony, Ember Run Loop and mocking your API. It
is common for Ember.js developers to struggle when writing tests. However, there are some tips
which could save your time and energy.
Examples
Waiting for promises in tests in elegant way
You can make function passed to test() method async - then you can use await keyword. Your
test will wait until Promises resolve and testing asynchronous code becomes easier and more
readable. In the following example call that returns a Promise is changeset.validate(). Please
notice also wrapping set call in Ember.run. Setting quantity has asynchronous effects (observers,
computed properties) and thus we need to wrap it in Ember.run.
await changeset.validate();
assert.ok(!changeset.get('error.quantity'));
Ember.run(() => {
changeset.set('quantity', -1);
});
await changeset.validate();
assert.equal(changeset.get('error.quantity.validation.length'), 1);
assert.ok(!changeset.get('isValid'));
});
https://riptutorial.com/ 23
Credits
S.
Chapters Contributors
No
Asynchronous Tasks
2 Sukima, user2708383, wdspkr
in Components
Component -
communication
3 Cameron, knownasilya, locks, Xinyang Li
between child to
parent component.
Currency formatting
4 Alan Mabry, Andrius
template helper
6 Debugging nem035
How to import
7 JavaScript Rafalsonn
library/plugin
How to update
8 Ember, Ember Data Cameron, ddoria921, heat, locks
and Ember CLI
Initialize Foundation
or Bootstrap on
9 Rafalsonn
ember-cli in a proper
way
https://riptutorial.com/ 24