我有一个函数,这是代码:
this.federalPriceComputed = ko.pureComputed(
function() {
return ko.utils.arrayMap(this.lineItems(), function(item) {
var total = item.price() * item.federalTax()
return formatCurrency(total);
});
}, this
).extend({ throttle: 500 });
this.statePriceComputed = ko.pureComputed(
function() {
return ko.utils.arrayMap(this.lineItems(), function(item) {
var total = item.price() * item.stateTax()
return formatCurrency(total);
});
}, this
).extend({ throttle: 500 });
当我运行我的代码时,它说statePriceComputed is not defined
。
我试图将所有代码保留在模型对象中。
如果我这样做,它会起作用。
ko.utils.arrayForEach(myModel.lineItems(), function(item) {
item.federalPriceComputed = ...
item.statePriceComputed = ....
}
);
更多信息:
ko.observableArray.fn.withIndex = function (keyName) {
"use strict";
var index = ko.computed(function () {
var list, keys;
list = this() || []; // the internal array
keys = {}; // a place for key/value
ko.utils.arrayForEach(list, function (v) {
if (keyName) { // if there is a key
keys[ko.utils.unwrapObservable(v[keyName])] = v; // use it
} else {
keys[v] = v;
}
});
return keys;
}, this);
// also add a handy add on function to find
// by key ... uses a closure to access the
// index function created above
this.findByKey = function (key) {
return index()[key];
};
return this;
};
当我绑定变量时,我这样做了
if (stateTax.length) {
stateTax.attr("data-bind", "text: formatCurrency($data.lineItems.findByKey(\"" + itemId + "\").statePriceComputed())");
}
// similar code for federal tax
你能给出建议为什么选项#1 不起作用。