Search code examples
ember.jsember-datajavascript-frameworkember-model

Using DS.model or Ember.model or Ember.Object when defining a model?


This screencast : http://www.embercasts.com/episodes/getting-started-with-ember-model used Ember.model to create a person model like this:

App.Person = Ember.Model.extend({
    name : Ember.attr()
})


The docs give this example using Ember.Object

App.Person = Ember.Object.extend({
    say : function(thing) {
        alert(thing);
    }
});

Further, under defining models section this example is given which uses DS.model

App.Person = DS.Model.extend({
  firstName: DS.attr('string'),
  lastName: DS.attr('string'),
  birthday: DS.attr('date'),

  fullName: function() {
    return this.get('firstName') + ' ' + this.get('lastName');
  }.property('firstName', 'lastName')
});

What is the difference between these three and when to use which?


Solution

  • Ember.Object - mother of all

    As stated in this very illustrative article on Ember.Object:

    Almost every object in Ember.js is derived from a common object: Ember.Object. This object is used as the basis for views, controllers, models, and even the application itself.

    This simple architectural decision is responsible for much of the consistency across Ember. Because every object has been derived from the same core object, they all share some core capabilities. Every Ember object can observe the properties of other objects, bind their properties to the properties of other objects, specify and update computed properties, and much more.

    Now to the differences and when you might use them depending on your use case.

    Ember.Object

    • is the ember.js main class for all Ember objects. It is a subclass of Ember.CoreObject with the Ember.Observable mixin applied.
    • you use it to create arbitrary objects, this class is also the foundation to make data binding possible.

    Ember.Model

    • is used by the ember-model lib and extends Ember.Object
    • you use this class to define a model if you use ember-model as your persistence library

    DS.Model

    • is used by ember-data and it's the ORM system base class which also extends from Ember.Object
    • you use it when you use ember-data as your persistence library to define your models and relationships etc.

    Hope it helps.