Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

knockout.js - knockoutJS execute callback after foreach finishes rendering

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...