Reputation: 2295
Here is example: http://jsfiddle.net/valin/W4ubQ/
As you can see array instantiated by function (this.features
) is working. But array instantiated by ko.mapping (this.featuresFromJS
) is working only for view, but not inside javascript function. How should I instantiate featuresFromJS
or whatever to compute lowTotal
?
Any help is appreciated.
Upvotes: 1
Views: 60
Reputation: 2314
Hope this will help:
function objFeatures(name, price) {
return {
name: ko.observable(name),
price: ko.observable(price)
}
}
var AppViewModel = function () {
var self = this;
self.featuresFromJS = ko.observableArray();
self.features = ko.observableArray([
new objFeatures("Feature1", 20),
new objFeatures("Feature2", 50)]);
var data = '[{"name":"Feature3","price":20},{"name":"Feature4","price":50}]';
ko.mapping.fromJSON(data, {}, self.featuresFromJS);
self.lowTotal = ko.computed(function () {
var total = 0;
ko.utils.arrayForEach(this.featuresFromJS(), function (item) {
alert("hooray!");
total += item.price();
});
return total;
}, self);
self.grandTotal = ko.computed(function () {
var total = 0;
ko.utils.arrayForEach(this.features(), function (item) {
total += item.price();
});
return total;
}, self);
};
ko.applyBindings(new AppViewModel());
Upvotes: 1