我不确定这是否合理。不确定如何说出来。
基本上我有这个。
function Line(id, name, equipType, model, height, length, loadsWeek, weight, width, pallets) {
this.id = ko.observable(id);
this.name = ko.observable(name);
this.height = ko.observable(height);
this.length = ko.observable(length);
this.weight = ko.observable(weight);
this.width = ko.observable(width);
this.model = ko.observable(model);
this.equipType = ko.observable(equipType);
this.loadsWeek = ko.observable(loadsWeek);
this.perimeter = ko.dependentObservable(function() {
return parseInt(this.height()) + parseInt(this.length())
}, this);
var mapped = ko.utils.arrayMap(pallets, function(pallet) {
return new Pallet(pallet.id, pallet.name, pallet.height, pallet.width, this)
});
this.pallets = ko.observableArray(mapped);
}
function Pallet(id, name, height, width, line) {
this.id = ko.observable(id);
this.name = ko.observable(name);
this.height = ko.observable(height);
this.width = ko.observable(width);
this.line = ko.dependentObservable(line);
//calculate something here that uses a variable from Line
}
现在在托盘中我需要访问线对象以从中获取值。我要做的计算需要Line对象的值。这段代码现在不能正常工作,因为我显然无法将“this”(行)传递给Pallet对象。
这是代码的其余部分
var viewModel = {
lines: ko.observableArray([]),
activeTab: ko.observable()
};
$.getJSON("/json/all/lines", { customer_id : customer_id } , function(data) {
//ko.mapping.fromJS(data, null, viewModel.lines);
var mappedData = ko.utils.arrayMap(data, function(line) {
return new Line(line.id, line.name, line.equipType, line.model, line.height, line.length, line.loadsWeek, line.weight, line.width, line.pallets)
});
});
答案 0 :(得分:5)
问题可能是您传递给arrayMap的匿名函数中的this
与您认为的this
不同。
尝试类似:
var that = this;
var mapped = ko.utils.arrayMap(pallets, function(pallet) {
return new Pallet(pallet.id, pallet.name, pallet.height, pallet.width, that)
});
------然后
function Pallet(id, name, height, width, line) {
this.id = ko.observable(id);
this.name = ko.observable(name);
this.height = ko.observable(height);
this.width = ko.observable(width);
this.line = ko.dependentObservable(line);
//calculate something here that uses a variable from Line
this.something = ko.observable(function() {
return this.line().somethingFromParent();
});
}