Search code examples
ember.jsember-data

Ember Data Snapshot and how to detect changes?


I'm writing my own adapter/serializer. In order to send data to backend, I have to detect changes in DS.Snapshot and original Ember object. For ordinary attributes, it is possible to changedAttributes() but I did not found a way how to detect changes in hasMany relations.

I can detect new relation using snapshot.hasMany('foo') and changedAttributes(). But this approach is not able to find deleted relations.


Solution

  • Ember (2.x) does not track relations (e.g. hasMany) but it is possible to use ember-addon ember-data-change-tracker that can almost do it. It allows you to (auto-)save the current state of relations and afterwards you can compare this 'saved' (=old state) with the current state. You have to find a difference by yourself. A simple example from adapter:

    snapshot.hasMany('users').length <-- current count of relations
    snapshot.record.savedTrackerValue('users').length <-- old count of relations
    

    Thanks to Christoper for pointing me to the right direction.