user2134216
user2134216

Reputation: 60

How to get notified on model changes in generic way with ember data

I am using Ember and Ember Data and I would like to listen to any changes relevant for a specific model.

For example in my app I could have an Order model with two fields - attr1 and attr2.

The two use cases/questions are:

  1. How to get notified when new Order instances get added or deleted to/from store. Something like store.on(modelName, 'deleted/added', listener). modelName in this case would equal 'order'.
  2. How to get notified on any change within all models of specific type in the store. Something like store.on(modelName, 'modelUpdated', listener). I don't want to specify in which attributes I am interested because I am interested in any change in any attribute.

Any ideas and pointers are really appreciated.

Upvotes: 0

Views: 677

Answers (2)

masciugo
masciugo

Reputation: 1191

ember-data provides lifecycle callbacks for DS.Model objects. Have a look to the events panel of the doc.

Upvotes: 1

user663031
user663031

Reputation:

You can extend the store to achieve the behavior in point 1. We will use an event name of "added:modelName".

this.store.reopen(Ember.Evented, {
    createRecord(model) { 
        this.trigger('added' + ':' + model);
        return this._super(...arguments);
    }
}

Point 2 is harder.

To listen from somewhere:

listen: function() { this.store.on('added:order'), this.handleAddedOrder; }

Upvotes: 0

Related Questions