vendredi 20 mai 2016

Observe changes in internal array Ember Object

I want to observe changes inside an Ember object created inside an Ember Service.

export default Ember.Service.extend({
  internalCache: Ember.Object.create(),

  setInternalCache: function setTestObj(itemId, relation, content) {
    let arr, myarr, ref, internalCache;
    internalCache = this.get('internalCache');

    if (!((ref = internalCache[itemId]) != null ? ref[relation] : void 0)) {
      internalCache[itemId] || (internalCache[itemId] = {});
      internalCache[itemId][relation] = [];
    }

    arr = Ember.copy((internalCache[itemId][relation]), false);
    content.map(function (elem) {
      return arr.pushObject(elem);
    });

    myarr = internalCache[itemId][relation];
    myarr.replace(0, arr.length, Ember.copy(arr, false));
  }});

The internalCache object properties can be observed, but this object will be eventually be filled with an internal object with several properties to be arrays. I want to observe changes when elements are added/removes on those arrays. Say a structure like:

internalCache: {
  "identifier12": {
    attachments: [1, 2],
    children: [ ... ]
  }
}

The attachments array property is set using the setInternalCache function and it successfully modifies the attachments array property inside the identifier12 property of internalCache.

What I've tried so far:

cache: Ember.inject.service('cache');

itemAttachmentsObserver: Ember.observer('cache.internalCache.identifier12', function() {
  console.log('foo');
}).on('init')

To see if nested modified props would trigger the observer, nothing.

itemAttachmentsObserver: Ember.observer('cache.internalCache.identifier12.@each', function() {
  console.log('bar');
}).on('init')

and

itemAttachmentsObserver: Ember.observer('cache.internalCache.identifier12.@each.attachments.[]', function() {
  console.log('baz')
}).on('init')

But I can't make the observer trigger when the attachments array is modified.




Aucun commentaire:

Enregistrer un commentaire