在foreach完成渲染后,knockoutJS执行回调 [英] knockoutJS execute callback after foreach finishes rendering

查看:131
本文介绍了在foreach完成渲染后,knockoutJS执行回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中,我想在KnockoutJS foreach 绑定完成渲染所有项目之后执行函数或回调

我知道我可以简单地通过检查我是否在最后一个元素(我发现这里执行代码后,最后一个项目已经被渲染)。
但是使用这个我的回调函数将被调用每次一个新的元素或记录被渲染。


我只想执行一次我的回调函数(用于执行)。

更新

另一个解决方案是在knockout.js完成渲染所有元素后成功回调。但是再次使用这个我的回调函数会在每次渲染一个新的元素的时候被调用。

解决方案

我认为一个很好的解决方案对于这种类型的问题是使用自定义绑定。它会是这样的:

  ko.bindingHandlers.doSomething = {
update:function(element,valueAccessor){
ko.utils.unwrapObservable(valueAccessor()); //获取obs数组的依赖关系

//根据元素(容器)
}
}




< / p> ; ul data-bind =foreach:items,doSomething:items>
< li> ...< / li>
< / ul>

doSomething 需要获取自己的依赖关系到项目,作为 foreach 更新在它自己的计算observable和KO 3.0绑定里面是独立的。您也可以将选项传递给 doSomething ,然后通过访问observableArray获取依赖关系,这通过 allBindingsAccessor()。foreach 第三个参数),如果你总是把它与 foreach

这里是一个样本,随机化背景颜色observableArray中的每个元素,每当每次更改到observbaleArray时: http://jsfiddle.net/rniemeyer/SCqaS/


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).

UPDATE

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)
    }
}

You would use it like:

<ul data-bind="foreach: items, doSomething: items">
     <li>...</li>
</ul>

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.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆