Friday, 6 September 2013

Refresh non observable binding in Knockout

Refresh non observable binding in Knockout

I have a collection of objects. The collection is a observableArray
because I want to update my view when the collection changes in size.
I do not want to make the fields in the collections items observable
because they are almost always constants and I do not want the overhead
and ugly syntax of observables.
But there is that one extremely rare operation that need to update the
values of ALL the elements in the list.
I don't mind to have a performance penalty in this case (a few seconds),
but I don't know how to "rebind" the entire list and refresh the bindings.
I tried using valueHasMutated on the list, but do not have the desired
effect. I made a fiddle with a simplified view of my problem.
class Item
constructor: (value) ->
@value = value
class ItemsList
constructor: () ->
@items = ko.observableArray (new Item(1) for number in [1..10])
rareOperation: () =>
item.value = item.value + 1 for item in @items()
@items.valueHasMutated()
ko.applyBindings( new ItemsList() )
http://jsfiddle.net/EXkWg/2/
I know that it is not the normal use-case of Knockout, and the right
answer is to use observables, but in this case I prefer something else.

No comments:

Post a Comment