3

假设我CollectionView在 ember.js 中有一个。

最初,假设该content属性绑定到一个包含几个元素的数组。CollectionView 将渲染这些元素,一旦它们在 DOM 中,didInsertElement就应该首先为每个 childViews 调用,最后为它CollectionView自己调用。

让我们假设content发生了变化(例如添加了新项目,或者完全替换了数组)。将CollectionView追加新的孩子,或完全替换孩子。DOM 会相应地更新。但是没有didInsertElement要求CollectionView.

在对 DOM 进行所有更改后,我想运行一些自定义 JS。类似于 didRerenderElement 或 didUpdateElement 钩子。

我尝试了什么但不起作用?

  1. 我不能将此代码放入didInsertElementCollectionView 中,因为每次数组更改和 DOM 更新时都不会触发该代码。
  2. 我尝试观察content,但观察者总是会在实际 DOM 更新发生之前触发。
  3. 我尝试观察childViews,但情况类似。

对我有用的一个晦涩的解​​决方案是:

App.MyCollectionView = Ember.View.extend({
  childrenReady: 1, // anything, value doesn't matter

  itemViewClass: Ember.View.extend({
    didInsertElement: function () {
      this.get('parentView').notifyPropertyChange('childrenReady');
    }
  }),

  childrenGotReady: function () {
    if (this.get('childViews').everyProperty('state', 'inDOM')) {
      // run that custom JS code here (e.g. apply jQuery masonry to the elements)
    }
  }.observes('childrenReady')      

});

但这太模糊了,也容易出现其他问题。

我读过这篇文章:如何在重新渲染 Ember 视图的一部分时运行代码?但这不适用于CollectionViews。

我在我的应用程序的很多地方都遇到了这个问题,我真的希望 emberjs 有一个标准的方法来解决这个问题。

4

2 回答 2

4

这是一个观察子元素数组的示例观察者,并在所有子元素触发其 didInsertElement 时回调。

addOnDidInsertObserver: function(children, callback) {
    var options = {
        willChange: function() {},
        didChange: function(children, removing, adding) {
            var insertedChildren = [];
            adding.forEach(function(added) {
                var onInsertElement = function() {
                    // remove this call back now (cleanup)
                    added.off('didInsertElement', onInsertElement)
                    // capture the child
                    insertedChildren.push(added);
                    // if all of the new children are rendered, fire
                    if (insertedChildren.length == adding.length) {
                        callback(insertedChildren);
                    }
                };

                added.on('didInsertElement', onInsertElement);
            });
        }
    };

    children.addEnumerableObserver(this, options);
    return {'context':this, 'children':children, 'options':options};
}

removeOnDidInsertObserver: function(observer) {
    observer.children.removeEnumerableObserver(observer.context, observer.options);
},
于 2012-11-21T14:18:38.827 回答
0

didInsertElement 也应该适用于 collectionView。来源。但是不能直接操作 CollectionView 的 childViews 属性。相反,从其内容属性中添加、删除、替换项目。这将触发对其呈现的 HTML 的适当更改。也调用 didInsertElement。

于 2012-11-21T12:34:50.037 回答