Ember data:The coolest construction zone in JS today
By: Jason Cox & Javon Harper@jasocox@javonharper
ShareMySpace.com
Introduction
What is Ember Data?
Automagic everything!
● Persistence/Retrieval
● Updating UI (no event handling/triggering!)
● Relationships
Why are we using it?
● Because we are using ember.js
● It's new, shiny, and fun!
● It's saved a lot of time with writing code (mostly)
● Fewer lines of code == fewer bugs
Defining Models
Getting Started
Make your model filejavascripts/models/user.js
App.User = DS.Model.extend({// Stuff goes here
});
Types
App.User = DS.Model.extend({firstName: DS.attr(‘string’),lastName: DS.attr(‘string’)
});
Type: string, number, boolean, and date
Calculated Fields/Methods
App.User = DS.Model.extend({firstName: DS.attr(‘string’),lastName: DS.attr(‘string’),
fullName: function() { return this.get('firstName') + ' ' + this.get('lastName');}.property('firstName', 'lastName')
});
Relationships
App.User = DS.Model.extend({firstName: DS.attr(‘string’),lastName: DS.attr(‘string’),
fullName: function() { return this.get('firstName') + ' ' + this.get('lastName');}.property('firstName', 'lastName'),
profile: DS.belongsTo(‘App.Profile’),favorites: DS.hasMany(‘App.Beer’)
});
Code samplehttps://github.com/nicholaides/ember-sample-app
REST Adapter
What is it?
● Used by Ember Data for all loading and storing
● Allows several customizations (more following)
● Could write your own (e.g., for XML or RESTlike)
Retrieving Your Data
var firstPost = App.Post.find(1);
var posts = App.Post.find();
var people = App.Person.find({ name: "Peter" });
var transaction = this.get('store').transaction();
transaction.add(user);
user.set('age', 100);
transaction.commit();
Updating Your Data
● Pluralization (i.e., person: people)
● Endpoint Path
● Host
● Transformations (more following)
Adapter Configurations
Transformations
When string, number, boolean, and date aren't enough.
DS.RESTAdapter.registerTransform('coordinatePoint', { serialize: function(value) { return [value.get('x'), value.get('y')]; }, deserialize: function(value) { return Ember.create({ x: value[0], y: value[1] }); }});
App.Cursor = DS.Model.extend({ position: DS.attr('coordinatePoint')});
Adapter Conveniences
● Sideloading, or embedding associations
● Identity map (ember data)
● "Everything in Ember.js is bindings-aware"
Model Lifecycle
States & Events
● Offers a handful of flags to express state
● isLoaded, isDirty, isValid + more
● Provides helpful events
● didCreate, didUpdate, didDelete,
becameError, didLoad + more
Examples
<div {{ bindAttr class=”beer.isDirty:modified”}}>
beer.on(‘becameError’, function() {invokeBlindRage();
});
Code samplehttps://github.com/javonharper/ember-sample-app
Other Frameworks
Gotchas
Questions & Answers
Links
http://emberjs.com/guides/models/http://discuss.emberjs.com/https://github.com/emberjs/datahttp://stackoverflow.com/questions/tagged/ember.js