DS.Store Class packages/ember-data/lib/system/store.js:61

The store contains all of the data for records loaded from the server. It is also responsible for creating instances of DS.Model that wrap the individual data for a record, so that they can be bound to in your Handlebars templates.

Define your application's store like this:

1
MyApp.Store = DS.Store.extend();

Most Ember.js applications will only have a single DS.Store that is automatically created by their Ember.Application.

You can retrieve models from the store in several ways. To retrieve a record for a specific id, use DS.Store's find() method:

1
2
store.find('person', 123).then(function (person) {
});

If your application has multiple DS.Store instances (an unusual case), you can specify which store should be used:

1
2
store.find('person', 123).then(function (person) {
});

By default, the store will talk to your backend using a standard REST mechanism. You can customize how the store talks to your backend by specifying a custom adapter:

1
MyApp.ApplicationAdapter = MyApp.CustomAdapter

You can learn more about writing a custom adapter by reading the DS.Adapter documentation.

Store createRecord() vs. push() vs. pushPayload() vs. update()

The store provides multiple ways to create new record objects. They have some subtle differences in their use which are detailed below:

createRecord is used for creating new records on the client side. This will return a new record in the created.uncommitted state. In order to persist this record to the backend you will need to call record.save().

push is used to notify Ember Data's store of new or updated records that exist in the backend. This will return a record in the loaded.saved state. The primary use-case for store#push is to notify Ember Data about record updates that happen outside of the normal adapter methods (for example SSE or Web Sockets).

pushPayload is a convenience wrapper for store#push that will deserialize payloads if the Serializer implements a pushPayload method.

update works like push, except it can handle partial attributes without overwriting the existing record properties.

Note: When creating a new record using any of the above methods Ember Data will update DS.RecordArrays such as those returned by store#all(), store#findAll() or store#filter(). This means any data bindings or computed properties that depend on the RecordArray will automatically be synced to include the new or updated record values.

Show:

_generateId

(type) String private

If possible, this method asks the adapter to generate an ID for a newly created record.

Parameters:

type String

Returns:

String
if the adapter can generate one, an ID

_load

(type, data, partial) private

This internal method is used by push.

Parameters:

type String or subclass of DS.Model
data Object
partial Boolean
the data should be merged into the existing data, not replace it.

_normalizeTypeKey

(type) String private

All typeKeys are camelCase internally. Changing this function may require changes to other normalization hooks (such as typeForRoot).

Parameters:

type String

Returns:

String
if the adapter can generate one, an ID

_scheduledDestroy

private

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

adapterFor

(type) private

Returns the adapter for a given type.

Parameters:

type subclass of DS.Model

Returns:

DS.Adapter

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.

all

(type) DS.RecordArray

This method returns a filtered array that contains all of the known records for a given type.

Note that because it's just a filter, it will have any locally created records of the type.

Also note that multiple calls to all for a given type will always return the same RecordArray.

Example

1
var localPosts = store.all('post');

Parameters:

type String or subclass of DS.Model

Returns:

DS.RecordArray

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

buildRecord

(type, id, data) DS.Model private

Build a brand new record for a given type, ID, and initial data.

Parameters:

type subclass of DS.Model
id String
data Object

Returns:

DS.Model
record

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

create

(arguments) static

Creates an instance of a class. Accepts either no arguments, or an object containing values to initialize the newly instantiated object with.

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

var tom = App.Person.create({
  name: 'Tom Dale'
});

tom.helloWorld(); // alerts "Hi, my name is Tom Dale".

create will call the init function if defined during Ember.AnyObject.extend

If no arguments are passed to create, it will not set values to the new instance during initialization:

1
2
var noName = App.Person.create();
noName.helloWorld(); // alerts undefined

NOTE: For performance reasons, you cannot declare methods or computed properties during create. You should instead declare methods and computed properties when using extend or use the createWithMixins shorthand.

Parameters:

arguments

createRecord

(type, properties) DS.Model

Create a new record in the current store. The properties passed to this method are set on the newly created record.

To create a new instance of App.Post:

1
2
3
store.createRecord('post', {
  title: "Rails is omakase"
});

Parameters:

type String
properties Object
a hash of properties to set on the newly created record.

Returns:

DS.Model
record

createWithMixins

(arguments) static

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

Parameters:

arguments

dataWasUpdated

(type, record) private

If the adapter updates attributes or acknowledges creation or deletion, the record will notify the store to update its membership in any filters. To avoid thrashing, this method is invoked only once per

run loop per record.

Parameters:

type Class
record DS.Model

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

(record)

For symmetry, a record can be deleted via the store.

Example

1
2
3
4
5
var post = store.createRecord('post', {
  title: "Rails is omakase"
});

store.deleteRecord(post);

Parameters:

record DS.Model

dematerializeRecord

(record) private

When a record is destroyed, this un-indexes it and removes it from any record arrays so it can be GCed.

Parameters:

record DS.Model

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

didSaveRecord

(record, data) private

This method is called once the promise returned by an adapter's createRecord, updateRecord or deleteRecord is resolved.

If the data provides a server-generated ID, it will update the record and the store's indexes.

Parameters:

record DS.Model
the in-flight record
data Object
optional data (see above)

didUpdateAll

(type)

Parameters:

type DS.Model

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

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

fetchAll

(type, array) Promise private

Parameters:

type DS.Model
array DS.RecordArray

Returns:

Promise
promise

fetchRecord

(record) Promise private

This method is called by findById if it discovers that a particular type/id pair hasn't been loaded yet to kick off a request to the adapter.

Parameters:

record DS.Model

Returns:

Promise
promise

filter

(type, query, filter) DS.PromiseArray

Takes a type and filter function, and returns a live RecordArray that remains up to date as new records are loaded into the store or created locally.

The callback function takes a materialized record, and returns true if the record should be included in the filter and false if it should not.

The filter function is called once on all records for the type when it is created, and then once on each newly loaded or created record.

If any of a record's properties change, or if it changes state, the filter function will be invoked again to determine whether it should still be in the array.

Optionally you can pass a query which will be triggered at first. The results returned by the server could then appear in the filter if they match the filter function.

Example

1
2
3
4
5
6
7
8
store.filter('post', {unread: true}, function(post) {
  return post.get('unread');
}).then(function(unreadPosts) {
  unreadPosts.get('length'); // 5
  var unreadPost = unreadPosts.objectAt(0);
  unreadPost.set('unread', false);
  unreadPosts.get('length'); // 4
});

Parameters:

type String or subclass of DS.Model
query Object
optional query
filter Function

Returns:

DS.PromiseArray

find

(type, id, preload) Promise

This is the main entry point into finding records. The first parameter to this method is the model's name as a string.


To find a record by ID, pass the id as the second parameter:

1
store.find('person', 1);

The find method will always return a promise that will be resolved with the record. If the record was already in the store, the promise will be resolved immediately. Otherwise, the store will ask the adapter's find method to find the necessary data.

The find method will always resolve its promise with the same object for a given type and id.


You can optionally preload specific attributes and relationships that you know of by passing them as the third argument to find.

For example, if your Ember route looks like /posts/1/comments/2 and your API route for the comment also looks like /posts/1/comments/2 if you want to fetch the comment without fetching the post you can pass in the post to the find call:

1
store.find('comment', 2, {post: 1});

If you have access to the post model you can also pass the model itself:

1
2
3
store.find('post', 1).then(function (myPostModel) {
  store.find('comment', 2, {post: myPostModel});
});

This way, your adapter's find or buildURL method will be able to look up the relationship on the record and construct the nested URL without having to first fetch the post.


To find all records for a type, call find with no additional parameters:

1
store.find('person');

This will ask the adapter's findAll method to find the records for the given type, and return a promise that will be resolved once the server returns the values.


To find a record by a query, call find with a hash as the second parameter:

1
store.find('person', { page: 1 });

This will ask the adapter's findQuery method to find the records for the query, and return a promise that will be resolved once the server responds.

Parameters:

type String or subclass of DS.Model
id Object|String|Integer|null
preload Object
- optional set of attributes and relationships passed in either as IDs or as actual models

Returns:

Promise
promise

findAll

(type) DS.AdapterPopulatedRecordArray private

This method returns an array of all records adapter can find. It triggers the adapter's findAll method to give it an opportunity to populate the array with records of that type.

Parameters:

type String or subclass of DS.Model

findBelongsTo

(owner, link, relationship) Promise private

Parameters:

owner DS.Model
link Any
relationship Relationship

Returns:

Promise
promise

findById

(type, id, preload) Promise private

This method returns a record for a given type and id combination.

Parameters:

type String or subclass of DS.Model
id String|Integer
preload Object
- optional set of attributes and relationships passed in either as IDs or as actual models

Returns:

Promise
promise

findByIds

(type, ids) Promise private

This method makes a series of requests to the adapter's find method and returns a promise that resolves once they are all loaded.

Parameters:

type String
ids Array

Returns:

Promise
promise

findHasMany

(owner, link, type) Promise private

If a relationship was originally populated by the adapter as a link (as opposed to a list of IDs), this method is called when the relationship is fetched.

The link (which is usually a URL) is passed through unchanged, so the adapter can make whatever request it wants.

The usual use-case is for the server to register a URL as a link, and then use that URL in the future to make a request for the relationship.

Parameters:

owner DS.Model
link Any
type String or subclass of DS.Model

Returns:

Promise
promise

findMany

(owner, records, type, resolver) DS.ManyArray private

Parameters:

owner DS.Model
records Array
type String or subclass of DS.Model
resolver Resolver

Returns:

DS.ManyArray
records

findQuery

(type, query) Promise private

This method delegates a query to the adapter. This is the one place where adapter-level semantics are exposed to the application.

Exposing queries this way seems preferable to creating an abstract query language for all server-side queries, and then require all adapters to implement them.

This method returns a promise, which is resolved with a RecordArray once the server returns.

Parameters:

type String or subclass of DS.Model
query Any
an opaque query to be used by the adapter

Returns:

Promise
promise

flushPendingSave

private

This method is called at the end of the run loop, and flushes any records passed into scheduleSave

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.

getById

(type, id) DS.Model|null

Get a record by a given type and ID without triggering a fetch.

This method will synchronously return the record if it is available in the store, otherwise it will return null. A record is available if it has been fetched earlier, or pushed manually into the store.

Note: This is an synchronous method and does not return a promise.

1
2
3
var post = store.getById('post', 1);

post.get('id'); // 1

Parameters:

type String or subclass of DS.Model
id String|Integer

Returns:

DS.Model|null
record

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.

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

hasRecordForId

(type, id) Boolean

Returns true if a record for a given type and ID is already loaded.

Parameters:

type String or subclass of DS.Model
id String|Integer

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

private

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

metaForType

(type, metadata)

If you have some metadata to set for a type you can call metaForType.

Parameters:

type String or subclass of DS.Model
metadata Object

metadataFor

(type) Object

This method returns the metadata for a specific type.

Parameters:

type String or subclass of DS.Model

Returns:

Object

modelFor

(key) subclass of DS.Model

Returns a model class for a particular key. Used by methods that take a type key (like find, createRecord, etc.)

Parameters:

key String or subclass of DS.Model

Returns:

subclass of DS.Model

normalize

(type, payload) Object

normalize converts a json payload into the normalized form that push expects.

Example

1
2
3
4
5
socket.on('message', function(message) {
  var modelName = message.model;
  var data = message.data;
  store.push(modelName, store.normalize(modelName, data));
});

Parameters:

type String
The name of the model type for this payload
payload Object

Returns:

Object
The normalized payload

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

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

push

(type, data) DS.Model

Push some data for a given type into the store.

This method expects normalized data:

  • The ID is a key named id (an ID is mandatory)
  • The names of attributes are the ones you used in your model's DS.attrs.
  • Your relationships must be:
    • represented as IDs or Arrays of IDs
    • represented as model instances
    • represented as URLs, under the links key

For this model:

1
2
3
4
5
6
App.Person = DS.Model.extend({
  firstName: DS.attr(),
  lastName: DS.attr(),

  children: DS.hasMany('person')
});

To represent the children as IDs:

1
2
3
4
5
6
{
  id: 1,
  firstName: "Tom",
  lastName: "Dale",
  children: [1, 2, 3]
}

To represent the children relationship as a URL:

1
2
3
4
5
6
7
8
{
  id: 1,
  firstName: "Tom",
  lastName: "Dale",
  links: {
    children: "/people/1/children"
  }
}

If you're streaming data or implementing an adapter, make sure that you have converted the incoming data into this form.

This method can be used both to push in brand new records, as well as to update existing records.

Parameters:

type String or subclass of DS.Model
data Object

Returns:

DS.Model
the record that was created or updated.

pushMany

(type, datas) Array

If you have an Array of normalized data to push, you can call pushMany with the Array, and it will call push repeatedly for you.

Parameters:

type String or subclass of DS.Model
datas Array

Returns:

Array

pushPayload

(type, payload)

Push some raw data into the store.

This method can be used both to push in brand new records, as well as to update existing records. You can push in more than one type of object at once. All objects should be in the format expected by the serializer.

1
2
3
4
5
6
7
8
9
10
11
12
App.ApplicationSerializer = DS.ActiveModelSerializer;

var pushData = {
  posts: [
    {id: 1, post_title: "Great post", comment_ids: [2]}
  ],
  comments: [
    {id: 2, comment_body: "Insightful comment"}
  ]
}

store.pushPayload(pushData);

By default, the data will be deserialized using a default serializer (the application serializer if it exists).

Alternatively, pushPayload will accept a model type which will determine which serializer will process the payload. However, the serializer itself (processing this data via normalizePayload) will not know which model it is deserializing.

1
2
3
4
App.ApplicationSerializer = DS.ActiveModelSerializer;
App.PostSerializer = DS.JSONSerializer;
store.pushPayload('comment', pushData); // Will use the ApplicationSerializer
store.pushPayload('post', pushData); // Will use the PostSerializer

Parameters:

type String
Optionally, a model used to determine which serializer will be used
payload Object

recordForId

(type, id) DS.Model private

Returns id record for a given type and ID. If one isn't already loaded, it builds a new record and leaves it in the empty state.

Parameters:

type String or subclass of DS.Model
id String|Integer

Returns:

DS.Model
record

recordIsLoaded

(type, id) Boolean

This method returns if a certain record is already loaded in the store. Use this function to know beforehand if a find() will result in a request or that it will be a cache hit.

Example

1
2
3
4
store.recordIsLoaded('post', 1); // false
store.find('post', 1).then(function() {
  store.recordIsLoaded('post', 1); // true
});

Parameters:

type String or subclass of DS.Model
id String

Returns:

Boolean

recordWasError

(record) private

This method is called once the promise returned by an adapter's createRecord, updateRecord or deleteRecord is rejected (with anything other than a DS.InvalidError).

Parameters:

record DS.Model

recordWasInvalid

(record, errors) private

This method is called once the promise returned by an adapter's createRecord, updateRecord or deleteRecord is rejected with a DS.InvalidError.

Parameters:

record DS.Model
errors Object

reloadRecord

(record) Promise private

This method is called by the record's reload method.

This method calls the adapter's find method, which returns a promise. When that promise resolves, reloadRecord will resolve the promise returned by the record's reload.

Parameters:

record DS.Model

Returns:

Promise
promise

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

scheduleSave

(record, resolver) private

This method is called by record.save, and gets passed a resolver for the promise that record.save returns.

It schedules saving to happen at the end of the run loop.

Parameters:

record DS.Model
resolver Resolver

serialize

(record, options) private

Returns a JSON representation of the record using a custom type-specific serializer, if one exists.

The available options are:

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

Parameters:

record DS.Model
the record to serialize
options Object
an options hash

serializerFor

(type) DS.Serializer private

Returns an instance of the serializer for a given type. For example, serializerFor('person') will return an instance of App.PersonSerializer.

If no App.PersonSerializer is found, this method will look for an App.ApplicationSerializer (the default serializer for your entire application).

If no App.ApplicationSerializer is found, it will fall back to an instance of DS.JSONSerializer.

Parameters:

type String
the record to serialize

Returns:

DS.Serializer

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

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

typeMapFor

(type) Object private

Returns a map of IDs to client IDs for a given type.

Parameters:

type subclass of DS.Model

Returns:

Object
typeMap

unloadAll

(type)

This method unloads all of the known records for a given type.

1
store.unloadAll('post');

Parameters:

type String or subclass of DS.Model

unloadRecord

(record)

For symmetry, a record can be unloaded via the store. Only non-dirty records can be unloaded.

Example

1
2
3
store.find('post', 1).then(function(post) {
  store.unloadRecord(post);
});

Parameters:

record DS.Model

update

(type, data) DS.Model

Update existing records in the store. Unlike push, update will merge the new data properties with the existing properties. This makes it safe to use with a subset of record attributes. This method expects normalized data.

update is useful if your app broadcasts partial updates to records.

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

store.get('person', 1).then(function(tom) {
  tom.get('firstName'); // Tom
  tom.get('lastName'); // Dale

  var updateEvent = {id: 1, firstName: "TomHuda"};
  store.update('person', updateEvent);

  tom.get('firstName'); // TomHuda
  tom.get('lastName'); // Dale
});

Parameters:

type String
data Object

Returns:

DS.Model
the record that was updated.

updateId

(record, data) private

When an adapter's createRecord, updateRecord or deleteRecord resolves with data, this method extracts the ID from the supplied data.

Parameters:

record DS.Model
data Object

willDestroy

Override to implement teardown.

Show:

adapter

{DS.Adapter|String}

The adapter to use to communicate to a backend server or other persistence layer.

This can be specified as an instance, class, or string.

If you want to specify App.CustomAdapter as a string, do:

1
adapter: 'custom'

Default: DS.RESTAdapter

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

defaultAdapter

private

This property returns the adapter, after resolving a possible string key.

If the supplied adapter was a class, or a String property path resolved to a class, this property will instantiate the class.

This property is cacheable, so the same instance of a specified adapter class should be used for the lifetime of the store.

Returns:

DS.Adapter

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