knockoutJS execute callback after foreach finishes

2020-02-05 07:20发布

问题:

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.

回答1:

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/