Observe change on any attribute of an Ember Data

[亡魂溺海] 提交于 2019-12-25 03:34:07

问题


Is this possible? Something like .observes('_data'), but not.

The use case is, I have a Decays mixin that has some CPs that say how long its been since a model has been updated. I'd like these CPs to be able to update if any of the model's attrs have changed. isDirty also won't work, since my use case uses store.push to update the model.


回答1:


I don't think there's a built-in way to do it, but it wouldn't be very difficult to make one. Just create a base class for all of your models and override the set function. Something like this:

var BaseModel = DS.Model.extend({
    set: function(keyName, value) {
        var ret = this._super.apply(this, arguments);
        var attributes = Ember.get(this.constructor, 'attributes');

        if (attributes[keyName]) {
            this.trigger('attributeChanged');
        }

        return ret;
    }
});

Then, you can listen for changes to any attribute like this:

model.on('attributeChanged', function() {});

I think you can even do something like this in the case of a controller or similar object (although I haven't tested it):

Controller.extend(Ember.Evented, {
    modelPropertyChanged: function() {

    }.on('model.attributeChanged')
});


来源:https://stackoverflow.com/questions/29110623/observe-change-on-any-attribute-of-an-ember-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!