在foreach完成渲染后,knockoutJS执行回调

编程入门 行业动态 更新时间:2024-10-23 13:38:18
本文介绍了在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时: jsfiddle/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: jsfiddle/rniemeyer/SCqaS/

更多推荐

在foreach完成渲染后,knockoutJS执行回调

本文发布于:2023-11-25 04:06:08,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:回调   foreach   knockoutJS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!