문제

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.

도움이 되었습니까?

해결책

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());
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top