Reputation: 5533
I am trying to update the umber shown in red to reflect the positions of each item in an observableArray when one item has been repositioned. You can see my current code here: http://jsfiddle.net/BV87N/
It's not quite behaving the way I would expect it to. I have a feeling it's because the items and their properties inside of the array are not observable themselves.
But I'm not quite sure how to get this to work.
ko.bindingHandlers.sortable.afterMove = function () {
self.adjustOrder();
};
self.adjustOrder = function () {
for (var i = 0, j = self.items().length; i < j; i++) {
self.items()[i].sortOrder = i;
};
};
Upvotes: 1
Views: 2737
Reputation: 139758
This is very explicitly stated in the documentation of observable Arrays
Key point: An observableArray tracks which objects are in the array, not the state of those objects
Simply putting an object into an observableArray doesn’t make all of that object’s properties themselves observable. Of course, you can make those properties observable if you wish, but that’s an independent choice.
So you need to make your sortOrder
properties ko.observable()
(there is a plugin called Knockout Mapping which could help in that) and then change your adjustOrder
to
self.adjustOrder = function () {
for (var i = 0, j = self.items().length; i < j; i++) {
self.items()[i].sortOrder(i);
};
};
Demo JSFiddle.
SideNote: But in your case you don't really need any on your sortOrder
properties because the order of the items in the items
is the sort order. So in your bindings you can use just $index
(binding context property) instead of sortOrder
.
Demo JSFiddle.
Upvotes: 6