仅从knockout.js开始,但在尝试根据2个不同computed
s
observableArray
方法时遇到了一些麻烦
使用knockout.js网站上的文档,我创建了以下viewmodel:
var Cart = function() {
var self = this;
self.Products = ko.observableArray([]);
self.Products2 = ko.observableArray([]);
self.Messages = ko.observableArray([]);
self.TotalAmount = ko.computed(function() {
var result = 0;
ko.utils.arrayForEach(
this.Products().concat(this.Products2()),
function(item) {
result+=item.AmountIncludingVAT();
}
);
return result;
});
};
这样做会引发错误"Uncaught TypeError: Object #<error> has no method 'concat'
。
我知道这个函数名为arrayPushAll
,但它是一个破坏性的函数,会改变原来的observableArray
。 (我不认为这是我想要的东西。)
有没有 clean 方式来实现我想要做的事情?或者我是否必须对arrayForEach
进行两次不同的调用,每个阵列一次?
答案 0 :(得分:6)
变化:
this.Products().concat(this.Products2()),
为:
self.Products().concat(self.Products2()),
在TotalAmount ko.computed函数中。
计算上下文中的 this
是指全局对象而不是视图模型。因此,您需要使用之前分配了正确self
值的this
变量。
工作示例 - http://jsfiddle.net/55kZp/
答案 1 :(得分:5)
concat
对我不起作用..我做了push
self.Products.push.apply(
self.Products, self.Products2()
);