DS.Model Class packages/ember-data/lib/system/relationships/ext.js:23

These observers observe all belongsTo relationships on the record. See relationships/ext to see how these observers get their dependencies.

Show:

_create

private static

Alias DS.Model's create method to _create. This allows us to create DS.Model instances from within the store, but if end users accidentally call create() (instead of createRecord()), we can raise an error.

_debugInfo

private

Provides info about the model for debugging purposes by grouping the properties into more semantic groups.

Meant to be used by debugging tools such as the Chrome Ember Extension.

  • Groups all attributes in "Attributes" group.
  • Groups all belongsTo relationships in "Belongs To" group.
  • Groups all hasMany relationships in "Has Many" group.
  • Groups all flags in "Flags" group.
  • Flags relationship CPs as expensive properties.

_preloadData

(preload) private

When a find request is triggered on the store, the user can optionally pass in attributes and relationships to be preloaded. These are meant to behave as if they came back from the server, except the user obtained them out of band and is informing the store of their existence. The most common use case is for supporting client side nested URLs, such as /posts/1/comments/2 so the user can do store.find('comment', 2, {post:1}) without having to fetch the post.

Preloaded data can be attributes and relationships passed in either as IDs or as actual models.

Parameters:

preload Object

_scheduledDestroy

private

Invoked by the run loop to actually destroy the object. This is scheduled for execution by the destroy method.

adapterDidCommit

If the adapter did not return a hash in response to a commit, merge the changed attributes and relationships into the existing saved data.

adapterDidDirty

private

adapterDidError

private

adapterDidInvalidate

private

adapterWillCommit

private

addObserver

(key, target, method)

Adds an observer on a property.

This is the core method used to register an observer for a property.

Once you call this method, any time the key's value is set, your observer will be notified. Note that the observers are triggered any time the value is set, regardless of whether it has actually changed. Your observer should be prepared to handle that.

You can also pass an optional context parameter to this method. The context will be passed to your observer method whenever it is triggered. Note that if you add the same target/method pair on a key multiple times with different context parameters, your observer will only be called once with the last context you passed.

Observer Methods

Observer methods you pass should generally have the following signature if you do not pass a context parameter:

1
fooDidChange: function(sender, key, value, rev) { };

The sender is the object that changed. The key is the property that changes. The value property is currently reserved and unused. The rev is the last property revision of the object when it changed, which you can use to detect if the key value has really changed or not.

If you pass a context parameter, the context will be passed before the revision like so:

1
fooDidChange: function(sender, key, value, context, rev) { };

Usually you will not need the value, context or revision parameters at the end. In this case, it is common to write observer methods that take only a sender and key value as parameters or, if you aren't interested in any of these values, to write an observer that has no parameters at all.

Parameters:

key String
The key to observer
target Object
The target object to invoke
method String|Function
The method to invoke.

beginPropertyChanges

Ember.Observable

Begins a grouping of property changes.

You can use this method to group property changes so that notifications will not be sent until the changes are finished. If you plan to make a large number of changes to an object at one time, you should call this method at the beginning of the changes to begin deferring change notifications. When you are done making changes, call endPropertyChanges() to deliver the deferred change notifications and end deferring.

Returns:

Ember.Observable

cacheFor

(keyName) Object

Returns the cached value of a computed property, if it exists. This allows you to inspect the value of a computed property without accidentally invoking it if it is intended to be generated lazily.

Parameters:

keyName String

Returns:

Object
The cached value of the computed property, if any

changedAttributes

Object

Returns an object, whose keys are changed properties, and value is an [oldProp, newProp] array.

Example

1
2
3
4
5
6
7
8
App.Mascot = DS.Model.extend({
  name: attr('string')
});

var person = store.createRecord('person');
person.changedAttributes(); // {}
person.set('name', 'Tomster');
person.changedAttributes(); // {name: [undefined, 'Tomster']}

Returns:

Object
an object, whose keys are changed properties, and value is an [oldProp, newProp] array.

clearRelationships

private

create

private static

Override the class' create() method to raise an error. This prevents end users from inadvertently calling create() instead of createRecord(). The store is still able to create instances by calling the _create() method. To create an instance of a DS.Model use store.createRecord.

createWithMixins

(arguments) static

Equivalent to doing extend(arguments).create(). If possible use the normal create method instead.

Parameters:

arguments

decrementProperty

(keyName, decrement) Number

Set the value of a property to the current value minus some amount.

1
2
player.decrementProperty('lives');
orc.decrementProperty('health', 5);

Parameters:

keyName String
The name of the property to decrement
decrement Number
The amount to decrement by. Defaults to 1

Returns:

Number
The new property value

deleteRecord

Marks the record as deleted but does not save it. You must call save afterwards if you want to persist it. You might use this method if you want to allow the user to still rollback() a delete after it was made.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
App.ModelDeleteRoute = Ember.Route.extend({
  actions: {
    softDelete: function() {
      this.controller.get('model').deleteRecord();
    },
    confirm: function() {
      this.controller.get('model').save();
    },
    undo: function() {
      this.controller.get('model').rollback();
    }
  }
});

destroy

Ember.Object

Destroys an object by setting the isDestroyed flag and removing its metadata, which effectively destroys observers and bindings.

If you try to set a property on a destroyed object, an exception will be raised.

Note that destruction is scheduled for the end of the run loop and does not happen immediately. It will set an isDestroying flag immediately.

Returns:

Ember.Object
receiver

destroyRecord

Promise

Same as deleteRecord, but saves the record immediately.

Example

1
2
3
4
5
6
7
8
9
10
App.ModelDeleteRoute = Ember.Route.extend({
  actions: {
    delete: function() {
      var controller = this.controller;
      controller.get('model').destroyRecord().then(function() {
        controller.transitionToRoute('model.index');
      });
    }
  }
});

Returns:

Promise
a promise that will be resolved when the adapter returns successfully or rejected if the adapter returns with an error.

didDefineProperty

(proto, key, value)

This Ember.js hook allows an object to be notified when a property is defined.

In this case, we use it to be notified when an Ember Data user defines a belongs-to relationship. In that case, we need to set up observers for each one, allowing us to track relationship changes and automatically reflect changes in the inverse has-many array.

This hook passes the class being set up, as well as the key and value being defined. So, for example, when the user does this:

1
2
3
DS.Model.extend({
  parent: DS.belongsTo('user')
});

This hook would be called with "parent" as the key and the computed property returned by DS.belongsTo as the value.

Parameters:

proto Object
key String
value Ember.ComputedProperty

eachAttribute

(callback, target) static

Iterates through the attributes of the model, calling the passed function on each attribute.

The callback method you provide should have the following signature (all parameters are optional):

1
function(name, meta);
  • name the name of the current property in the iteration
  • meta the meta object for the attribute property in the iteration

Note that in addition to a callback, you can also pass an optional target object that will be set as this on the context.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
App.Person = DS.Model.extend({
  firstName: attr('string'),
  lastName: attr('string'),
  birthday: attr('date')
});

App.Person.eachAttribute(function(name, meta) {
  console.log(name, meta);
});

// prints:
// firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"}
// lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"}
// birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"}

Parameters:

callback Function
The callback to execute
target Object
The target object to use

eachComputedProperty

(callback, binding)

Iterate over each computed property for the class, passing its name and any associated metadata (see metaForProperty) to the callback.

Parameters:

callback Function
binding Object

eachRelatedType

(callback, binding) static

Given a callback, iterates over each of the types related to a model, invoking the callback with the related type's class. Each type will be returned just once, regardless of how many different relationships it has with a model.

Parameters:

callback Function
the callback to invoke
binding Any
the value to which the callback's `this` should be bound

eachRelationship

(callback, binding)

Given a callback, iterates over each of the relationships in the model, invoking the callback with the name of each relationship and its relationship descriptor.

Parameters:

callback Function
the callback to invoke
binding Any
the value to which the callback's `this` should be bound

eachTransformedAttribute

(callback, target) static

Iterates through the transformedAttributes of the model, calling the passed function on each attribute. Note the callback will not be called for any attributes that do not have an transformation type.

The callback method you provide should have the following signature (all parameters are optional):

1
function(name, type);
  • name the name of the current property in the iteration
  • type a string containing the name of the type of transformed applied to the attribute

Note that in addition to a callback, you can also pass an optional target object that will be set as this on the context.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
App.Person = DS.Model.extend({
  firstName: attr(),
  lastName: attr('string'),
  birthday: attr('date')
});

App.Person.eachTransformedAttribute(function(name, type) {
  console.log(name, type);
});

// prints:
// lastName string
// birthday date

Parameters:

callback Function
The callback to execute
target Object
The target object to use

endPropertyChanges

Ember.Observable

Ends a grouping of property changes.

You can use this method to group property changes so that notifications will not be sent until the changes are finished. If you plan to make a large number of changes to an object at one time, you should call beginPropertyChanges() at the beginning of the changes to defer change notifications. When you are done making changes, call this method to deliver the deferred change notifications and end deferring.

Returns:

Ember.Observable

extend

(mixins, arguments) static

Creates a new subclass.

1
2
3
4
5
App.Person = Ember.Object.extend({
  say: function(thing) {
    alert(thing);
   }
});

This defines a new subclass of Ember.Object: App.Person. It contains one method: say().

You can also create a subclass from any existing class by calling its extend() method. For example, you might want to create a subclass of Ember's built-in Ember.View class:

1
2
3
4
App.PersonView = Ember.View.extend({
  tagName: 'li',
  classNameBindings: ['isAdministrator']
});

When defining a subclass, you can override methods but still access the implementation of your parent class by calling the special _super() method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
App.Person = Ember.Object.extend({
  say: function(thing) {
    var name = this.get('name');
    alert(name + ' says: ' + thing);
  }
});

App.Soldier = App.Person.extend({
  say: function(thing) {
    this._super(thing + ", sir!");
  },
  march: function(numberOfHours) {
    alert(this.get('name') + ' marches for ' + numberOfHours + ' hours.')
  }
});

var yehuda = App.Soldier.create({
  name: "Yehuda Katz"
});

yehuda.say("Yes");  // alerts "Yehuda Katz says: Yes, sir!"

The create() on line #17 creates an instance of the App.Soldier class. The extend() on line #8 creates a subclass of App.Person. Any instance of the App.Person class will not have the march() method.

You can also pass Mixin classes to add additional properties to the subclass.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
App.Person = Ember.Object.extend({
  say: function(thing) {
    alert(this.get('name') + ' says: ' + thing);
  }
});

App.SingingMixin = Mixin.create({
  sing: function(thing){
    alert(this.get('name') + ' sings: la la la ' + thing);
  }
});

App.BroadwayStar = App.Person.extend(App.SingingMixin, {
  dance: function() {
    alert(this.get('name') + ' dances: tap tap tap tap ');
  }
});

The App.BroadwayStar class contains three methods: say(), sing(), and dance().

Parameters:

mixins Mixin
One or more Mixin classes
arguments Object
Object containing values to use within the new class

get

(keyName) Object

Retrieves the value of a property from the object.

This method is usually similar to using object[keyName] or object.keyName, however it supports both computed properties and the unknownProperty handler.

Because get unifies the syntax for accessing all these kinds of properties, it can make many refactorings easier, such as replacing a simple property with a computed property, or vice versa.

Computed Properties

Computed properties are methods defined with the property modifier declared at the end, such as:

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

When you call get on a computed property, the function will be called and the return value will be returned instead of the function itself.

Unknown Properties

Likewise, if you try to call get on a property whose value is undefined, the unknownProperty() method will be called on the object. If this method returns any value other than undefined, it will be returned instead. This allows you to implement "virtual" properties that are not defined upfront.

Parameters:

keyName String
The property to retrieve

Returns:

Object
The property value or undefined.

getProperties

(list) Hash

To get the values of multiple properties at once, call getProperties with a list of strings or an array:

1
2
record.getProperties('firstName', 'lastName', 'zipCode');
// { firstName: 'John', lastName: 'Doe', zipCode: '10011' }

is equivalent to:

1
2
record.getProperties(['firstName', 'lastName', 'zipCode']);
// { firstName: 'John', lastName: 'Doe', zipCode: '10011' }

Parameters:

list String...|Array
of keys to get

Returns:

Hash

getWithDefault

(keyName, defaultValue) Object

Retrieves the value of a property, or a default value in the case that the property returns undefined.

1
person.getWithDefault('lastName', 'Doe');

Parameters:

keyName String
The name of the property to retrieve
defaultValue Object
The value to return if the property value is undefined

Returns:

Object
The property value or the defaultValue.

has

(name) Boolean

Checks to see if object has any subscriptions for named event.

Parameters:

name String
The name of the event

Returns:

Boolean
does the object have a subscription for event

hasObserverFor

(key) Boolean

Returns true if the object currently has observers registered for a particular key. You can use this method to potentially defer performing an expensive action until someone begins observing a particular property on the object.

Parameters:

key String
Key to check

Returns:

Boolean

incrementProperty

(keyName, increment) Number

Set the value of a property to the current value plus some amount.

1
2
person.incrementProperty('age');
team.incrementProperty('score', 2);

Parameters:

keyName String
The name of the property to increment
increment Number
The amount to increment by. Defaults to 1

Returns:

Number
The new property value

init

An overridable method called when objects are instantiated. By default, does nothing unless it is overridden during class definition.

Example:

1
2
3
4
5
6
7
8
9
10
11
App.Person = Ember.Object.extend({
  init: function() {
    alert('Name is ' + this.get('name'));
  }
});

var steve = App.Person.create({
  name: "Steve"
});

// alerts 'Name is Steve'.

NOTE: If you do override init for a framework class like Ember.View or Ember.ArrayController, be sure to call this._super() in your init declaration! If you don't, Ember may not have an opportunity to do important setup work, and you'll see strange behavior in your application.

loadedData

private

loadingData

(promise) private

Parameters:

promise Promise

metaForProperty

(key)

In some cases, you may want to annotate computed properties with additional metadata about how they function or what values they operate on. For example, computed property functions may close over variables that are then no longer available for introspection.

You can pass a hash of these values to a computed property like this:

1
2
3
4
person: function() {
  var personId = this.get('personId');
  return App.Person.create({ id: personId });
}.property().meta({ type: App.Person })

Once you've done this, you can retrieve the values saved to the computed property from your class like this:

1
MyClass.metaForProperty('person');

This will return the original hash that was passed to meta().

Parameters:

key String
property name

notFound

private

notifyPropertyChange

(keyName) Ember.Observable

Convenience method to call propertyWillChange and propertyDidChange in succession.

Parameters:

keyName String
The property key to be notified about.

Returns:

Ember.Observable

off

(name, target, method)

Cancels subscription for given name, target, and method.

Parameters:

name String
The name of the event
target Object
The target of the subscription
method Function
The function of the subscription

Returns:

this

on

(name, target, method)

Subscribes to a named event with given function.

1
2
3
person.on('didLoad', function() {
  // fired once the person has loaded
});

An optional target can be passed in as the 2nd argument that will be set as the "this" for the callback. This is a good way to give your function access to the object triggering the event. When the target parameter is used the callback becomes the third argument.

Parameters:

name String
The name of the event
target Object
The "this" binding for the callback
method Function
The callback to execute

Returns:

this

one

(name, target, method)

Subscribes a function to a named event and then cancels the subscription after the first time the event is triggered. It is good to use one when you only care about the first time an event has taken place.

This function takes an optional 2nd argument that will become the "this" value for the callback. If this argument is passed then the 3rd argument becomes the function.

Parameters:

name String
The name of the event
target Object
The "this" binding for the callback
method Function
The callback to execute

Returns:

this

propertyDidChange

(keyName) Ember.Observable

Notify the observer system that a property has just changed.

Sometimes you need to change a value directly or indirectly without actually calling get() or set() on it. In this case, you can use this method and propertyWillChange() instead. Calling these two methods together will notify all observers that the property has potentially changed value.

Note that you must always call propertyWillChange and propertyDidChange as a pair. If you do not, it may get the property change groups out of order and cause notifications to be delivered more often than you would like.

Parameters:

keyName String
The property key that has just changed.

Returns:

Ember.Observable

propertyWillChange

(keyName) Ember.Observable

Notify the observer system that a property is about to change.

Sometimes you need to change a value directly or indirectly without actually calling get() or set() on it. In this case, you can use this method and propertyDidChange() instead. Calling these two methods together will notify all observers that the property has potentially changed value.

Note that you must always call propertyWillChange and propertyDidChange as a pair. If you do not, it may get the property change groups out of order and cause notifications to be delivered more often than you would like.

Parameters:

keyName String
The property key that is about to change.

Returns:

Ember.Observable

pushedData

private

reload

Promise

Reload the record from the adapter.

This will only work if the record has already finished loading and has not yet been modified (isLoaded but not isDirty, or isSaving).

Example

1
2
3
4
5
6
7
App.ModelViewRoute = Ember.Route.extend({
  actions: {
    reload: function() {
      this.controller.get('model').reload();
    }
  }
});

Returns:

Promise
a promise that will be resolved with the record when the adapter returns successfully or rejected if the adapter returns with an error.

removeObserver

(key, target, method)

Remove an observer you have previously registered on this object. Pass the same key, target, and method you passed to addObserver() and your target will no longer receive notifications.

Parameters:

key String
The key to observer
target Object
The target object to invoke
method String|Function
The method to invoke.

reopen

Augments a constructor's prototype with additional properties and functions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
MyObject = Ember.Object.extend({
  name: 'an object'
});

o = MyObject.create();
o.get('name'); // 'an object'

MyObject.reopen({
  say: function(msg){
    console.log(msg);
  }
})

o2 = MyObject.create();
o2.say("hello"); // logs "hello"

o.say("goodbye"); // logs "goodbye"

To add functions and properties to the constructor itself, see reopenClass

reopenClass

Augments a constructor's own properties and functions:

1
2
3
4
5
6
7
8
9
10
MyObject = Ember.Object.extend({
  name: 'an object'
});

MyObject.reopenClass({
  canBuild: false
});

MyObject.canBuild; // false
o = MyObject.create();

In other words, this creates static properties and functions for the class. These are only available on the class and not on any instance of that class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
App.Person = Ember.Object.extend({
  name : "",
  sayHello : function(){
    alert("Hello. My name is " + this.get('name'));
  }
});

App.Person.reopenClass({
  species : "Homo sapiens",
  createPerson: function(newPersonsName){
    return App.Person.create({
      name:newPersonsName
    });
  }
});

var tom = App.Person.create({
  name : "Tom Dale"
});
var yehuda = App.Person.createPerson("Yehuda Katz");

tom.sayHello(); // "Hello. My name is Tom Dale"
yehuda.sayHello(); // "Hello. My name is Yehuda Katz"
alert(App.Person.species); // "Homo sapiens"

Note that species and createPerson are not valid on the tom and yehuda variables. They are only valid on App.Person.

To add functions and properties to instances of a constructor by extending the constructor's prototype see reopen

rollback

If the model isDirty this function will discard any unsaved changes

Example

1
2
3
4
5
record.get('name'); // 'Untitled Document'
record.set('name', 'Doc 1');
record.get('name'); // 'Doc 1'
record.rollback();
record.get('name'); // 'Untitled Document'

save

Promise

Save the record and persist any changes to the record to an external source via the adapter.

Example

1
2
3
4
5
6
record.set('name', 'Tomster');
record.save().then(function(){
  // Success callback
}, function() {
  // Error callback
});

Returns:

Promise
a promise that will be resolved when the adapter returns successfully or rejected if the adapter returns with an error.

send

(name, context) private

Parameters:

name String
context Object

serialize

(options) Object

Create a JSON representation of the record, using the serialization strategy of the store's adapter.

serialize takes an optional hash as a parameter, currently supported options are:

  • includeId: true if the record's ID should be included in the JSON representation.

Parameters:

options Object

Returns:

Object
an object whose values are primitive JSON values only

set

(keyName, value) Ember.Observable

Sets the provided key or path to the value.

This method is generally very similar to calling object[key] = value or object.key = value, except that it provides support for computed properties, the setUnknownProperty() method and property observers.

Computed Properties

If you try to set a value on a key that has a computed property handler defined (see the get() method for an example), then set() will call that method, passing both the value and key instead of simply changing the value itself. This is useful for those times when you need to implement a property that is composed of one or more member properties.

Unknown Properties

If you try to set a value on a key that is undefined in the target object, then the setUnknownProperty() handler will be called instead. This gives you an opportunity to implement complex "virtual" properties that are not predefined on the object. If setUnknownProperty() returns undefined, then set() will simply set the value on the object.

Property Observers

In addition to changing the property, set() will also register a property change with the object. Unless you have placed this call inside of a beginPropertyChanges() and endPropertyChanges(), any "local" observers (i.e. observer methods declared on the same object), will be called immediately. Any "remote" observers (i.e. observer methods declared on another object) will be placed in a queue and called at a later time in a coalesced manner.

Chaining

In addition to property changes, set() returns the value of the object itself so you can do chaining like this:

1
record.set('firstName', 'Charles').set('lastName', 'Jolley');

Parameters:

keyName String
The property to set
value Object
The value to set or `null`.

Returns:

Ember.Observable

setProperties

(hash) Ember.Observable

Sets a list of properties at once. These properties are set inside a single beginPropertyChanges and endPropertyChanges batch, so observers will be buffered.

1
record.setProperties({ firstName: 'Charles', lastName: 'Jolley' });

Parameters:

hash Hash
the hash of keys and values to set

Returns:

Ember.Observable

setupData

(data, partial) private

Parameters:

data Object
partial Boolean
the data should be merged into the existing data, not replace it.

toJSON

(options) Object

Use DS.JSONSerializer to get the JSON representation of a record.

toJSON takes an optional hash as a parameter, currently supported options are:

  • includeId: true if the record's ID should be included in the JSON representation.

Parameters:

options Object

Returns:

Object
A JSON representation of the object.

toString

String

Returns a string representation which attempts to provide more information than Javascript's toString typically does, in a generic way for all Ember objects.

1
2
3
App.Person = Em.Object.extend()
person = App.Person.create()
person.toString() //=> "<App.Person:ember1024>"

If the object's class is not defined on an Ember namespace, it will indicate it is a subclass of the registered superclass:

1
2
3
Student = App.Person.extend()
student = Student.create()
student.toString() //=> "<(subclass of App.Person):ember1025>"

If the method toStringExtension is defined, its return value will be included in the output.

1
2
3
4
5
6
7
App.Teacher = App.Person.extend({
  toStringExtension: function() {
    return this.get('fullName');
  }
});
teacher = App.Teacher.create()
teacher.toString(); //=> "<App.Teacher:ember1026:Tom Dale>"

Returns:

String
string representation

toggleProperty

(keyName) Object

Set the value of a boolean property to the opposite of it's current value.

1
starship.toggleProperty('warpDriveEngaged');

Parameters:

keyName String
The name of the property to toggle

Returns:

Object
The new property value

transitionTo

(name) private

Parameters:

name String

trigger

(name) private

Override the default event firing from Ember.Evented to also call methods with the given name.

Parameters:

name String

typeForRelationship

(name) subclass of DS.Model static

For a given relationship name, returns the model type of the relationship.

For example, if you define a model like this:

1
2
3
App.Post = DS.Model.extend({
  comments: DS.hasMany('comment')
});

Calling App.Post.typeForRelationship('comments') will return App.Comment.

Parameters:

name String
the name of the relationship

Returns:

subclass of DS.Model
the type of the relationship, or undefined

unloadRecord

private

updateRecordArrays

private

updateRecordArraysLater

private

willDestroy

Override to implement teardown.

Show:

attributes

{Ember.Map} static

A map whose keys are the attributes of the model (properties described by DS.attr) and whose values are the meta object for the property.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
App.Person = DS.Model.extend({
  firstName: attr('string'),
  lastName: attr('string'),
  birthday: attr('date')
});

var attributes = Ember.get(App.Person, 'attributes')

attributes.forEach(function(name, meta) {
  console.log(name, meta);
});

// prints:
// firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"}
// lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"}
// birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"}

clientId

{Number|String} private

The clientId property is a transient numerical identifier generated at runtime by the data store. It is important primarily because newly created objects may not yet have an externally generated id.

concatenatedProperties

Array

Defines the properties that will be concatenated from the superclass (instead of overridden).

By default, when you extend an Ember class a property defined in the subclass overrides a property with the same name that is defined in the superclass. However, there are some cases where it is preferable to build up a property's value by combining the superclass' property value with the subclass' value. An example of this in use within Ember is the classNames property of Ember.View.

Here is some sample code showing the difference between a concatenated property and a normal one:

1
2
3
4
5
6
7
8
9
10
11
12
13
App.BarView = Ember.View.extend({
  someNonConcatenatedProperty: ['bar'],
  classNames: ['bar']
});

App.FooBarView = App.BarView.extend({
  someNonConcatenatedProperty: ['foo'],
  classNames: ['foo']
});

var fooBarView = App.FooBarView.create();
fooBarView.get('someNonConcatenatedProperty'); // ['foo']
fooBarView.get('classNames'); // ['ember-view', 'bar', 'foo']

This behavior extends to object creation as well. Continuing the above example:

1
2
3
4
5
6
var view = App.FooBarView.create({
  someNonConcatenatedProperty: ['baz'],
  classNames: ['baz']
})
view.get('someNonConcatenatedProperty'); // ['baz']
view.get('classNames'); // ['ember-view', 'bar', 'foo', 'baz']

Adding a single property that is not an array will just add it in the array:

1
2
3
4
var view = App.FooBarView.create({
  classNames: 'baz'
})
view.get('classNames'); // ['ember-view', 'bar', 'foo', 'baz']

Using the concatenatedProperties property, we can tell to Ember that mix the content of the properties.

In Ember.View the classNameBindings and attributeBindings properties are also concatenated, in addition to classNames.

This feature is available for you to use throughout the Ember object model, although typical app developers are likely to use it infrequently. Since it changes expectations about behavior of properties, you should properly document its usage in each individual concatenated property (to not mislead your users to think they can override the property in a subclass).

Default: null

currentState

{Object} private

data

{Object} private

dirtyType

{String}

If the record is in the dirty state this property will report what kind of change has caused it to move into the dirty state. Possible values are:

  • created The record has been created by the client and not yet saved to the adapter.
  • updated The record has been updated by the client and not yet saved to the adapter.
  • deleted The record has been deleted by the client and not yet saved to the adapter.

Example

1
2
var record = store.createRecord('model');
record.get('dirtyType'); // 'created'

errors

{DS.Errors}

When the record is in the invalid state this object will contain any errors returned by the adapter. When present the errors hash typically contains keys corresponding to the invalid property names and values which are an array of error messages.

1
2
3
4
5
record.get('errors.length'); // 0
record.set('foo', 'invalid value');
record.save().then(null, function() {
  record.get('errors').get('foo'); // ['foo should be a number.']
});

fields

Ember.Map static

A map whose keys are the fields of the model and whose values are strings describing the kind of the field. A model's fields are the union of all of its attributes and relationships.

For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
App.Blog = DS.Model.extend({
  users: DS.hasMany('user'),
  owner: DS.belongsTo('user'),

  posts: DS.hasMany('post'),

  title: DS.attr('string')
});

var fields = Ember.get(App.Blog, 'fields');
fields.forEach(function(field, kind) {
  console.log(field, kind);
});

// prints:
// users, hasMany
// owner, belongsTo
// posts, hasMany
// title, attribute

id

{String}

All ember models have an id property. This is an identifier managed by an external source. These are always coerced to be strings before being used internally. Note when declaring the attributes for a model it is an error to declare an id attribute.

1
2
3
4
5
6
var record = store.createRecord('model');
record.get('id'); // null

store.find('model', 1).then(function(model) {
  model.get('id'); // '1'
});

isDeleted

{Boolean}

If this property is true the record is in the deleted state and has been marked for deletion. When isDeleted is true and isDirty is true, the record is deleted locally but the deletion was not yet persisted. When isSaving is true, the change is in-flight. When both isDirty and isSaving are false, the change has persisted.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var record = store.createRecord('model');
record.get('isDeleted');    // false
record.deleteRecord();

// Locally deleted
record.get('isDeleted');    // true
record.get('isDirty');      // true
record.get('isSaving');     // false

// Persisting the deletion
var promise = record.save();
record.get('isDeleted');    // true
record.get('isSaving');     // true

// Deletion Persisted
promise.then(function() {
  record.get('isDeleted');  // true
  record.get('isSaving');   // false
  record.get('isDirty');    // false
});

isDestroyed

Destroyed object property flag.

if this property is true the observers and bindings were already removed by the effect of calling the destroy() method.

Default: false

isDestroying

Destruction scheduled flag. The destroy() method has been called.

The object stays intact until the end of the run loop at which point the isDestroyed flag is set.

Default: false

isDirty

{Boolean}

If this property is true the record is in the dirty state. The record has local changes that have not yet been saved by the adapter. This includes records that have been created (but not yet saved) or deleted.

Example

1
2
3
4
5
6
7
8
var record = store.createRecord('model');
record.get('isDirty'); // true

store.find('model', 1).then(function(model) {
  model.get('isDirty'); // false
  model.set('foo', 'some value');
  model.get('isDirty'); // true
});

isEmpty

{Boolean}

If this property is true the record is in the empty state. Empty is the first state all records enter after they have been created. Most records created by the store will quickly transition to the loading state if data needs to be fetched from the server or the created state if the record is created on the client. A record can also enter the empty state if the adapter is unable to locate the record.

isError

{Boolean}

If true the adapter reported that it was unable to save local changes to the backend for any reason other than a server-side validation error.

Example

1
2
3
4
5
record.get('isError'); // false
record.set('foo', 'valid value');
record.save().then(null, function() {
  record.get('isError'); // true
});

isLoaded

{Boolean}

If this property is true the record is in the loaded state. A record enters this state when its data is populated. Most of a record's lifecycle is spent inside substates of the loaded state.

Example

1
2
3
4
5
6
var record = store.createRecord('model');
record.get('isLoaded'); // true

store.find('model', 1).then(function(model) {
  model.get('isLoaded'); // true
});

isLoading

{Boolean}

If this property is true the record is in the loading state. A record enters this state when the store asks the adapter for its data. It remains in this state until the adapter provides the requested data.

isNew

{Boolean}

If this property is true the record is in the new state. A record will be in the new state when it has been created on the client and the adapter has not yet report that it was successfully saved.

Example

1
2
3
4
5
6
var record = store.createRecord('model');
record.get('isNew'); // true

record.save().then(function(model) {
  model.get('isNew'); // false
});

isReloading

{Boolean}

If true the store is attempting to reload the record form the adapter.

Example

1
2
3
record.get('isReloading'); // false
record.reload();
record.get('isReloading'); // true

isSaving

{Boolean}

If this property is true the record is in the saving state. A record enters the saving state when save is called, but the adapter has not yet acknowledged that the changes have been persisted to the backend.

Example

1
2
3
4
5
6
7
var record = store.createRecord('model');
record.get('isSaving'); // false
var promise = record.save();
record.get('isSaving'); // true
promise.then(function() {
  record.get('isSaving'); // false
});

isValid

{Boolean}

If this property is true the record is in the valid state.

A record will be in the valid state when the adapter did not report any server-side validation failures.

relatedTypes

Ember.Array static

An array of types directly related to a model. Each type will be included once, regardless of the number of relationships it has with the model.

For example, given a model with this definition:

1
2
3
4
5
6
App.Blog = DS.Model.extend({
  users: DS.hasMany('user'),
  owner: DS.belongsTo('user'),

  posts: DS.hasMany('post')
});

This property would contain the following:

1
2
var relatedTypes = Ember.get(App.Blog, 'relatedTypes');
//=> [ App.User, App.Post ]

relationshipNames

Object static

A hash containing lists of the model's relationships, grouped by the relationship kind. For example, given a model with this definition:

1
2
3
4
5
6
App.Blog = DS.Model.extend({
  users: DS.hasMany('user'),
  owner: DS.belongsTo('user'),

  posts: DS.hasMany('post')
});

This property would contain the following:

1
2
3
4
5
var relationshipNames = Ember.get(App.Blog, 'relationshipNames');
relationshipNames.hasMany;
//=> ['users', 'posts']
relationshipNames.belongsTo;
//=> ['owner']

relationships

Ember.Map static

The model's relationships as a map, keyed on the type of the relationship. The value of each entry is an array containing a descriptor for each relationship with that type, describing the name of the relationship as well as the type.

For example, given the following model definition:

1
2
3
4
5
App.Blog = DS.Model.extend({
  users: DS.hasMany('user'),
  owner: DS.belongsTo('user'),
  posts: DS.hasMany('post')
});

This computed property would return a map describing these relationships, like this:

1
2
3
4
5
6
var relationships = Ember.get(App.Blog, 'relationships');
relationships.get(App.User);
//=> [ { name: 'users', kind: 'hasMany' },
//     { name: 'owner', kind: 'belongsTo' } ]
relationships.get(App.Post);
//=> [ { name: 'posts', kind: 'hasMany' } ]

relationshipsByName

Ember.Map static

A map whose keys are the relationships of a model and whose values are relationship descriptors.

For example, given a model with this definition:

1
2
3
4
5
6
App.Blog = DS.Model.extend({
  users: DS.hasMany('user'),
  owner: DS.belongsTo('user'),

  posts: DS.hasMany('post')
});

This property would contain the following:

1
2
3
4
5
var relationshipsByName = Ember.get(App.Blog, 'relationshipsByName');
relationshipsByName.get('users');
//=> { key: 'users', kind: 'hasMany', type: App.User }
relationshipsByName.get('owner');
//=> { key: 'owner', kind: 'belongsTo', type: App.User }

transformedAttributes

{Ember.Map} static

A map whose keys are the attributes of the model (properties described by DS.attr) and whose values are type of transformation applied to each attribute. This map does not include any attributes that do not have an transformation type.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
App.Person = DS.Model.extend({
  firstName: attr(),
  lastName: attr('string'),
  birthday: attr('date')
});

var transformedAttributes = Ember.get(App.Person, 'transformedAttributes')

transformedAttributes.forEach(function(field, type) {
  console.log(field, type);
});

// prints:
// lastName string
// birthday date

Show:

becameError

Fired when the record enters the error state.

becameInvalid

Fired when the record becomes invalid.

didCreate

Fired when the record is created.

didDelete

Fired when the record is deleted.

didLoad

Fired when the record is loaded from the server.

didUpdate

Fired when the record is updated.