我有一个viewmodel,它包含一个observablearray项。我有一个在viewmodel中使用的子类。我们可以从子类中的viewmodel访问observablearray吗?
这是我的viewmodel和子类
function XeroxSection() {
var self = this;
self.xrxcostupliftdesc = ko.observable('This is some data');
self.xrxdisticostgmdesc = ko.observable('This is some data');
self.xrxothercost1 = ko.observable('This is some data');
self.xrxothercost2 = ko.observable('This is some data');
self.xrxcostuplift = ko.observable(5);
self.xrxGM = ko.observable(10);
self.Sum = ko.computed(function () {
return 200;
});
}
function Configuration(data,xrxsec) {
var self = this;
self.configKey = data.pKey;
self.configName = data.configName;
self.configNumber = data.modelnumber;
self.configMTP = ko.observable(data.mTP);
self.configMDP = ko.observable(data.mDP);
self.confxrxcostuplift = ko.computed(function () {
return (self.configMTP() * xrxsec.xrxcostuplift()) / 100;
});
}
function AppViewModel() {
var self = this;
self.xrxSec = ko.observable(new XeroxSection());
self.Configurations = ko.observableArray([]);
self.Configurations.push(new Configuration({configName:
"PHASER 3010V/B PRINTER",mDP:10,mTP:20,pKey:1,modelNumber:"3010V_B"},
self.xrxSec()));
self.Configurations.push(new Configuration({
configName:"PHASER 4015V/B PRINTER",mDP:90,mTP:50,pKey:2,modelNumber:"3010V_B"},
self.xrxSec()));
self.selConfig = ko.observable();
}
var vm = new AppViewModel();
ko.applyBindings(vm);
从上面的代码中可以看出,我希望将所有配置的configMTP之和加到计算的observable" Sum"在XeroxSection类中。有人可以帮助解决这个问题吗?
这是JSFiddle http://jsfiddle.net/XMYPb/
答案 0 :(得分:4)
创建子模型时,将父项作为参数传递给子项
self.ChildProperty(new childprop (params,self))
这样你就可以在孩子
中访问这样的父母了var childprop = function(params , parent){
var self = this
self.Parent = ko.observable(parent)
}
现在您可以访问
self.Parent().Prop() // Prop is parent property