foreach完成渲染时的自定义绑定 [英] Custom binding for when foreach has finished rendering
问题描述
我有一个可观察的数组,其中的项目绑定到ul
.添加项目后,我需要计算整个li
项目集的宽度,以便可以将ul
元素的宽度设置为子li
元素的总宽度.
I have an observable array with items bound to an ul
. I need to calculate the width of the entire set of li
items once the items have been added so I can set the width of the ul
element to the total width of the child li
elements.
如何使用foreach
绑定进行此操作?
How can I go about doing this with a foreach
binding?
<div>
<h2 data-bind="visible: items().length">Test</h2>
<ul data-bind="foreach: { data: items, afterAdd: $root.myAfterAdd }">
<li data-bind="text: name"></li>
</ul>
</div>
和JavaScript:
And the JavaScript:
var viewModel = {
items: ko.observableArray([
{ name: "one" },
{ name: "two" },
{ name: "three" }
]),
myAfterAdd: function(element) {
if (element.nodeType === 1) {
alert("myAfterAdd");
}
},
addItem: function() {
this.items.push({ name: 'new' });
}
};
ko.applyBindings(viewModel);
// once foreach has finished rendering I have to set the width
// of the ul to be the total width of the children!
我尝试使用afterAdd
,以便在添加每个元素后可以更新" ul
的宽度,不幸的是,我发现afterAdd
不会针对初始项目触发!只有在推送其他个项目时才会触发...
I tried using afterAdd
so I can 'update' the width of the ul
after each element is added, unfortunately I have discovered that afterAdd
does not fire for the initial items! It will only fire when pushing additional items...
请注意,li
项内的内容的宽度未知:)
Note that the content inside the li
items will be of unknown width :)
有关示例场景,请参见此小提琴.
See this fiddle for a sample scenario.
推荐答案
经过多次搜索"后,我找到了解决方案.用foreach实现此目的的方法也是注册自定义事件处理程序:
After much 'googling' I have found the solution. The way to achieve this with a foreach is too register a custom event handler:
ko.bindingHandlers.runafter = {
update: function (element, valueAccessor, allBindingsAccessor) {
var value = valueAccessor();
setTimeout(function (element, value) {
if (typeof value != 'function' || ko.isObservable(value))
throw 'run must be used with a function';
value(element);
}, 0, element, value);
}
};
无论何时发生更新(如果值不可观察,则仅触发一次),此处理程序将触发.
This handler will fire whenever an update occurs (or just once if value is not an observable).
更重要的是,一旦foreach循环完成,它将触发!
More importantly it will fire once the foreach loop has completed!
请参见此处.
这篇关于foreach完成渲染时的自定义绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!