找出在Ember ArrayController中哪个单独的项目发生了变化

Find out which individual item changed in an Ember ArrayController

本文关键字:单独 项目 发生了 变化 Ember ArrayController      更新时间:2023-09-26

在一个Ember.ArrayController中,我有一个函数.observes()用于属性更改的模型的整个数组上的属性。

var FoosController = Ember.ArrayController.extend(Ember.Evented, {
    observesEachFooBar: function() {
        var foos = this.get('model');
        foos.forEach(function(foo) {
            //test if this foo has changed, then do something
        });
    }.observes('model.@each.bar'),
});

在这里,我手动测试其模型中的每个Foo。我怎样才能避免这样做,只给个人一个(或几个)?改变了吗?

Ember在SortableMixin中做到了这一点。您可以遵循相同的模式。

https://github.com/emberjs/ember.js/blob/v1.6.1/packages_es6/ember-runtime/lib/mixins/sortable.js L247

        forEach(sortProperties, function(sortProperty) {
          addObserver(item, sortProperty, this, 'contentItemSortPropertyDidChange');
        }, this);
      }, this);
    }
    return this._super(array, idx, removedCount, addedCount);
  },
  insertItemSorted: function(item) {
    var arrangedContent = get(this, 'arrangedContent');
    var length = get(arrangedContent, 'length');
    var idx = this._binarySearch(item, 0, length);
    arrangedContent.insertAt(idx, item);
  },
  contentItemSortPropertyDidChange: function(item) {
    var arrangedContent = get(this, 'arrangedContent'),
        oldIndex = arrangedContent.indexOf(item),
        leftItem = arrangedContent.objectAt(oldIndex - 1),
        rightItem = arrangedContent.objectAt(oldIndex + 1),
        leftResult = leftItem && this.orderBy(item, leftItem),
        rightResult = rightItem && this.orderBy(item, rightItem);
    if (leftResult < 0 || rightResult > 0) {
      arrangedContent.removeObject(item);
      this.insertItemSorted(item);
    }
  },

这里是一个使用addArrayObserver方法的示例,以及arrayContentWillChangearrayContentDidChange

App.IndexController = Em.ArrayController.extend({
  initializer: function() {
    this.addArrayObserver({
      arrayWillChange: Em.K,
      arrayDidChange: function(observedObj, start, removeCount, addCount) {
        if(!removeCount && !addCount) {
          alert('Array item at ' +start+ ' updated');
        }
      }
    });
  }.on('init'),
  actions: {
    updateData: function() {
      this.get('content').arrayContentWillChange(3, 0, 0);
      this.set('content.3.foo', 'foo3-updated');
      this.get('content').arrayContentDidChange(3, 0, 0);
    }
  }
});