假设我在 ember.js 中有一个 CollectionView
。
首先,假设 content
属性绑定(bind)到一个包含几个元素的数组。 CollectionView 将渲染这些元素,一旦它们进入 DOM,将首先为每个 childView 调用 didInsertElement
,最后为 CollectionView
本身调用。 p>
假设内容
发生变化(例如添加新项目或完全替换数组)。 CollectionView
将追加新的子项,或完全替换这些子项。 DOM 会相应更新。但是没有为 CollectionView
调用 didInsertElement
。
我想在对 DOM 进行所有更改后运行一些自定义 JS。类似于 didReenderElement 或 didUpdateElement Hook 。
我尝试了什么但不起作用?
- 我无法将此代码放入 CollectionView 的
didInsertElement
中,因为每次数组更改和 DOM 更新时都不会触发该代码。 - 我尝试观察
内容
,但观察者总是会在实际 DOM 更新发生之前触发。 - 我尝试观察
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')
});
但这太晦涩了,而且还容易出现其他问题。
我读过这个:How can I run code any time part of an Ember view is rerendered?但这不适用于CollectionView
。
我在我的应用程序的许多部分都遇到了这个问题,我真的希望 emberjs 有一个标准的方法来解决这个问题。
最佳答案
这是一个示例观察者,它监视子元素数组,并在所有子元素触发其 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);
},
关于ember.js - 使用 ember.js,当 CollectionView 重新渲染时如何收到通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13492736/