Get rid of the for
loop, it's messing things up (because the way how closures work, as @Andrew has pointed out correctly in the comments).
var ViewModel = function() {
var self = this;
self.multipler = ko.observable(1);
self.things = ko.observableArray();
self.fakeServerData = [
{ id: 1, properties: { name: '1', val: 1 }},
{ id: 2, properties: { name: '2', val: 2 }},
{ id: 3, properties: { name: '3', val: 3 }}
];
ko.utils.arrayForEach(self.fakeServerData, function (item) {
var props = item.properties,
multi = +self.multipler();
props.computed = ko.pureComputed(function () {
return multi * props.val;
});
});
};
ko.applyBindings(new ViewModel());
The rule of thumb is: Don't make functions in a loop. If you have to create functions, don't use a loop.
The way to avoid a loop is to use the native array functions (Array.prototype.forEach
) or their equivalents from various libraries, like knockout's own ko.utils.arrayForEach()
, jQuery's $.each
or underscore/lodash's _.forEach
and others.