【问题标题】:How to access parent viewmodel array in child class in knockout js如何在淘汰赛js中访问子类中的父视图模型数组
【发布时间】:2014-04-12 14:33:08
【问题描述】:

我有一个视图模型,它包含一个可观察的项目数组。我有一个在视图模型中使用的子类。我们可以从子类中的 viewmodel 访问 observablearray 吗?

这是我的视图模型和子类

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 总和转换为 XeroxSection 类中计算的可观察“总和”。有人可以帮助解决这个问题吗?

这里是 JSFiddle http://jsfiddle.net/XMYPb/

【问题讨论】:

    标签: knockout.js knockout-2.0


    【解决方案1】:

    当您创建子模型时,将父模型作为子模型的参数发送

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-25
      • 1970-01-01
      • 2015-04-01
      • 2015-09-30
      • 1970-01-01
      • 2015-08-19
      • 1970-01-01
      相关资源
      最近更新 更多