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是未定义的错误。我做错了什么?
答案 0 :(得分:2)
如果您位于“子”绑定上下文中,只有在使用$parent
或foreach
绑定时,才会填充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>