在foreach完成渲染后knockoutJS执行回调 [英] knockoutJS execute callback after foreach finishes rendering
问题描述
在我的代码中,我想在 KnockoutJS foreach
绑定完成渲染所有项目后执行函数或回调
In my code i want to execute function or callback just after KnockoutJS foreach
binding finishes rendering all the items
我知道我可以通过检查我是否在最后一个元素来做到这一点(我发现这里 在渲染最后一个项目后执行代码).
但是使用这个我的回调函数将在每次呈现新元素或记录时调用.
i know i can do this simply by check if I'm at the last element (i found that here execute code after the last item has been rendered).
But using this my callback function 'll be called each time a new element or record is rendered.
我只想执行一次回调函数(为了性能).
I want to execute my callback function only once (for performance).
更新
另一个解决方案在这里成功Knockout.js 完成渲染所有元素后的回调.但再次使用这个我的回调函数将在每次呈现新元素时调用.
another solution is here success callback after knockout.js finishes rendering all the elements. but again using this my callback function 'll be called each time a new element is rendered.
推荐答案
我认为解决此类问题的一个好方法是使用自定义绑定.它会是这样的:
I think that a good solution for this type of issue is to use a custom binding. It would be something like:
ko.bindingHandlers.doSomething = {
update: function(element, valueAccessor) {
ko.utils.unwrapObservable(valueAccessor()); //grab a dependency to the obs array
//do something based on "element" (the container)
}
}
你会像这样使用它:
<ul data-bind="foreach: items, doSomething: items">
<li>...</li>
</ul>
doSomething
需要获取自己对 items
的依赖,因为 foreach
在它自己的计算 observable 内部更新,并且在 KO 3.0 绑定中独立.您还可以将选项传递给 doSomething
,然后通过 allBindingsAccessor().foreach
(第三个参数)访问 observableArray 来获取依赖项,如果您总是将它与 foreach
.
The doSomething
needs to grab its own dependency to items
, as foreach
updates inside of its own computed observable and in KO 3.0 bindings will be independent. You could also pass options to doSomething
and then grab a dependency by accessing the observableArray through allBindingsAccessor().foreach
(the third arg), if you always couple it with foreach
.
这是一个示例,它在每次更改 observableArray 时随机化 observableArray 中每个元素的背景颜色:http://jsfiddle.net/rniemeyer/SCqaS/
Here is a sample that randomizes the background color of each element in the observableArray whenever once on each change to the observbaleArray: http://jsfiddle.net/rniemeyer/SCqaS/
这篇关于在foreach完成渲染后knockoutJS执行回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!