One of the chief advantages of having a front-end framework is being able to store and manipulate data entirely on the front-end, without needing to explicitly make AJAX requests. This is accomplished through a data layer, which for Ember is a library called ember-data. In this session, we'll look at how to use ember-data to set up front-end models and perform CRUD actions on them.
By now, you have already learned how to:
- Create nested view states and route to them appropriately.
- Set up resource routes.
- Model the user interface using components.
- Represent visual hierarchies with nested components.
- Register actions and click handlers on component objects.
- Pass data from routes to components, and from components to components.
By the end of this session, you should be able to:
- Generate a Model to represent a resource on the front-end.
- Extend an Adapter to connect your Model(s) to an API.
- Make Models accessible in templates by loading them through Routes.
- Create CRUD actions on a Route, and trigger them from Components.
- Add behavior to Route actions to perform CRUD on the Route's model.
- Fork and clone this repo.
- Run
npm install
andbower install
. - Clone listr-api into a subdirectory of ~/wdi/tmp and follow the instructions to setup the API.
- Start the api with
bin/rails server
- Start the client with
ember server
In the past few days, you've seen a whole lot of Ember's 'view' layer - the system governing how Ember responds to user behavior and controls what HTML gets rendered in the browser.
While this is all very nice, it's meaningless without an API. That's where
Ember's 'data' layer comes in, as implemented by an add-on library to Ember
called ember-data
.
ember-data
provides several Ember Classes for handling the exchange of
information between the client and the API, most notably Models (which
represent back-end resources as Ember Objects) and Adapters (which manage the
actual interactions with the underlying API(s)).
We'll start with the solution from ember-components
.
- Generate a
lists
route - Move ListR specifics from
index
route tolists
route - Link to
lists
route fromindex
route
ember generate route lists
- Generate a
list
model (for now, we'll leave items off) - Generate a
shopping-list/card
component as the top-level interface to lists - Copy the list title display to
shopping-list/card
(without any action) - Refactor the
lists
route template to useshopping-list/card
- Refactor the
lists
routemodel
method to use the ActiveModelAdapter
ember generate model list title:string hidden:boolean
This will create a new model.js
file inside app/list
. The README for the API
shows us the data we can expect at GET
/lists. Note that the
items returned are just ids. We specified the properties that we want the
ember-data
model to have. We could all of the properties from the API, but
we're leaving off items because we haven't created and item
model, yet.
DS.attr
is how we define attributes for our models. The default types are
'number', 'string', 'boolean', and 'date', but we can define our own if we
really need to. We can also use DS.attr
to specify a default value for a
given attribute by passing in an optional object as a second argument.
As we saw in the material on routing, each Route has a model
method that
exposes data to the template. Each Route also has a store
property which
refers to whatever data store our application is using (in this case,
ember-data), so to make the List model available in the lists
route, we
reference the store and query it for all instances.
export default Ember.Route.extend({
model () {
return this.get('store').findAll('list');
}
});
- Generate an
item
model - Add a hasMany to the
list
model - Generate a route for a single list
- Update
app/router.js
for the single list route - Add the
model
method to thelist
route - Invoke the
shopping-list
component from thelist
route template - Link to the
list
route from theshopping-list/card
template
ember generate model item content:string done:boolean list:belongs-to:list
ember generate route list
export default DS.Model.extend({
title: DS.attr('string'),
hidden: DS.attr('boolean'),
+ items: DS.hasMany('item'),
});
Router.map(function () {
this.route('lists');
- this.route('list');
+ this.route('list', { path: '/lists/:list_id' });
});
export default Ember.Route.extend({
+ model (params) {
+ return this.get('store').findRecord('list', params.list_id);
+ },
});
Now that we've refactored ListR to use data from the API, we'll move on to persisting changes.
Now that we have models loaded in our Routes, it's finally time to tie all of this together.
Before talking about CRUD, though, we should start by talking about something
you touched on in the material on Components: 'actions'. 'Actions' are a special
class of trigger-able events that are handled by the Ember.ActionHandler
Ember
Class. Like normal events, actions 'bubble up', moving from the leaf (i.e.
Template) to the root (i.e. the 'application' Route) until they are met by a
matching handler.
In Ember 1, action handlers inside the Controller were used to perform CRUD on the model. This made sense, since the Controller was responsible for managing all of the business data in our application, and since it mirrored how responsibilities were broken out in Rails. An action could be triggered in a Template and bubble up to a Controller, where it would cause that Controller to manipulate the given Model.
However, with the shift towards Components in Ember 2, a lot of the
functionality of Controllers has been made redundant and moved into other
entities within the app. In this case, Components and Routes both incorporate
Ember.ActionHandler
, so we can instead set our action handlers there. For
simplicity's sake, we'll put all handlers related to Model CRUD into the Route;
any other action handlers can be placed in either place.
Defining Action handlers in a Route is very easy. Simply open up the route.js
file and make the following addition:
import Ember from 'ember';
export default Ember.Route.extend({
model: function(...){
...
},
actions: {
create () { ... },
update () { ... },
destroy () { ... },
// ... etc
}
});
To trigger an action, you can add an {{action ... }}
helper to an element
(usually a button) - this will cause that element to launch the action whenever
it executes its defaults behavior (in the case of a button, being clicked).
In Ember applications that use Components (which will soon be all of them) the generally recommended strategy is to follow a 'data down, actions up' design pattern, which essentially means two things:
- All Components look to their parent element as a source of data to bind to; as a result, data changes propagate 'downwards' from parent to child.
- Implicit in the first point is that all changes to data take place in the parent. In order to effect changes to the data in a parent element, Components trigger their parents' actions; in this fashion, action invocations propagate 'upwards' from child to parent.
- In the
shopping-list/item
component- Make listItemCompleted a computed property alias of the item component
- Change toggleDone to send that action up
- In the
shopping-list
component- Add
toggleDone='toggleItemDone'
to invokingshopping-list/item
- Add the toggleItemDone action handler to send the action up
- Add
- In the
list
route- Add
toggleItemDone='toggleItemDone'
to invokingshopping-list
- Add the toggleItemDone action to the route
- Add
export default Ember.Component.extend({
tagName: 'li',
classNameBindings: ['listItemCompleted'],
- listItemCompleted: false,
+ listItemCompleted: Ember.computed.alias('item.done'),
actions: {
toggleDone () {
- return this.toggleProperty('listItemCompleted');
+ return this.sendAction('toggleDone', this.get('item'));
},
},
});
classNameBindings: ['listDetailHidden'],
listDetailHidden: false,
actions: {
+ toggleItemDone (item) {
+ return this.sendAction('toggleItemDone', item);
+ },
+
toggleListDetail () {
return this.toggleProperty('listDetailHidden');
},
model (params) {
return this.get('store').findRecord('list', params.list_id);
},
+
+ actions: {
+ toggleItemDone (item) {
+ item.toggleProperty('done');
+ item.save();
+ },
+ },
});
- In the
shopping-list/item
component- Add a button with text "Delete" and
{{action 'delete'}}
- Add a
delete
action to send that action up
- Add a button with text "Delete" and
- In the
shopping-list
component- Add
delete='deleteItem'
to invokingshopping-list/item
- Add the
deleteItem
action to send the action up
- Add
- In the
list
route- Add
deleteItem='deleteItem'
to invokingshopping-list
- Add the deleteItem action to the route
- Add
- In the
shopping-list
component- Add a form after
each
with{{action "createItem" on="submit"}}
- Add an input to the form with
value=newItem.content
- Add a
newItem
property - Add the
createItem
action to send the action up
- Add a form after
- In the
list
route- Add
createItem='createItem'
to invokingshopping-list
- Add the createItem action to the route
- Add
Does it work?
Unfortunately, no. The API uses a nested route for creating new list items.
This doesn't fit directly with ember-data
's modeling of APIs, so we have to do
some extra work.
We'll extend the default application adapter, included in ember-template
to
handle this case.
- Ember API : Ember.ActionHandler
- Ember API : DS.store
- Ember Data
- ember-data to ActiveRecord
- Ember core concepts
- Data Flow
- data down actions up
- All content is licensed under a CCBYNCSA 4.0 license.
- All software code is licensed under GNU GPLv3. For commercial use or alternative licensing, please contact legal@ga.co.