Knockout $ parent undefined

时间:2013-11-26 16:21:52

标签: knockout.js

Viewmodel是这样的:

Main_Vm = function () {
  var self = this;
  self.ChildViewModel = new OtherViewModel();
  self.ParProp = ko.observable();
};
var vmMain = new Main_Vm();

ko.applyBindings(vmMain, document.getElementById('mainArea'));
ko.applyBindings(vmMain.ChildViewModel, document.getElementById('childArea'));

如果我尝试在childArea中调用$ parent,我得到$ parent是未定义的错误。我做错了什么?

1 个答案:

答案 0 :(得分:2)

如果您位于“子”绑定上下文中,只有在使用$parentforeach绑定时,才会填充with。您可以阅读有关绑定上下文正常工作的更多信息here in the documentation.

在您当前的代码中,因为您直接在vmMain.ChildViewModel Knockout上应用绑定,不会为您创建子上下文,因此它不知道您的父vmMain对象。

您可以在OtherViewModel Main_Vm

中创建直接引用

或者您可以使用with binding

Main_Vm = function () {
  var self = this;
  self.ChildViewModel = new OtherViewModel();
  self.ParProp = ko.observable();
};
var vmMain = new Main_Vm();

ko.applyBindings(vmMain);

您的观点应如下所示:

<div id="mainArea">
 //.. do something with ParProp
</div>
<div id="childArea" data-bind="with: ChildViewModel">
  // do something with ChildViewModel's properties
  // or here you can use $parent to access your vmMain properties
</div>