knockout.js - mapping plugin - 如何添加ko.computed函数

时间:2012-08-19 19:43:19

标签: knockout.js

我试图让这个工作,但我没有做正确的事情。 我正在使用淘汰赛,接受json响应并将其映射到结账推车,我无法做的是添加一个功能后添加产品价格的总和。请参阅下文,了解我正在尝试做什么,

完全小提琴就在这里.. http://jsfiddle.net/justayles/Jeaua/26/

var jsonCart = {
    "globalshipping": 1.00,
    "globaltax": 5.00,
    "productitem": [
    {
        "img": '/Content/img/notavailable.jpg',
        "produrl": 'http://www.google.com',
        "prodtitle": 'Product1',
        "opt1": 'colour',
        "opt2": 'size',
        "qty": 3,
        "unitprice": 10.00,
        "shippingcost": 0.00,
        "like": true,
        "likediscount": 10,
        "taxable": true
    },
    {
        "img": '/Content/img/notavailable.jpg',
        "produrl": 'http://www.google.com',
        "prodtitle": 'Product1',
        "opt1": 'colour',
        "opt2": 'size',
        "qty": 1,
        "unitprice": 33.00,
        "shippingcost": 0.00,
        "like": false,
        "likediscount": 0,
        "taxable": false
    },
    {
        "img": '/Content/img/notavailable.jpg',
        "produrl": 'http://www.yahoo.com',
        "prodtitle": 'Product1',
        "opt1": 'colour',
        "opt2": 'size',
        "qty": 5,
        "unitprice": 21.00,
        "shippingcost": 0.00,
        "like": true,
        "likediscount": 10,
        "taxable": true
    }
    ]
};

var mappingOptions = {
    'productitem': {
        // overriding the default creation / initialization code
        create: function (options) {

            return (new (function () {

                // setup the computed binding
                this.calcPrice = ko.computed(function () {
                    return this.unitprice() * this.qty();
                }, this);

                ko.mapping.fromJS(options.data, {}, this);
            })(/* call the ctor here */));
        }
    }
};


var viewModel = ko.mapping.fromJS(jsonCart, mappingOptions );

viewModel.grandTotal = ko.computed(function() {
    var result = 0;
    ko.utils.arrayForEach(this.productitem, function(item) {
        result += item.calcPrice;
    });
    return result;
}, viewModel);

console.log(viewModel);

ko.applyBindings(viewModel);

1 个答案:

答案 0 :(得分:4)

修正:http://jsfiddle.net/Jeaua/27/

您忘记了productitemcalcPrice观察点上的括号。请记住,ko.mapping将数组转换为可观察数组,将值转换为可观察值。这些需要被称为函数,以便检索它们的实际值。

viewModel.grandTotal = ko.computed(function() {
        var result = 0;
        ko.utils.arrayForEach(this.productitem() /* parentheses */, function(item) {
            result += item.calcPrice(); /* parentheses */
        });
        return result;
}, viewModel);