gpt4 book ai didi

knockout.js - 映射插件 - 如何添加 ko.computed 函数

转载 作者:行者123 更新时间:2023-12-01 23:33:54 25 4
gpt4 key购买 nike

我正在努力让它发挥作用,但没有做对。我正在使用 knockout ,采用 json 响应并将其映射到结账车,我无法做的是在添加产品价格总和之后添加一个函数。请参阅下文了解我正在尝试做什么,

完整的 fiddle 在这里.. 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);

最佳答案

固定: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);

关于knockout.js - 映射插件 - 如何添加 ko.computed 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12029422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com