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/
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…