我对 javascript 淘汰赛中的 $parent 有疑问。
如果我有模型:
var Person = function () {
var self = this;
self.person_Id = ko.observable();
self.firstName = ko.observable();
self.lastName = ko.observable();
self.age = ko.observable();
self.role = ko.observable();
self.init = function (data) {
self.person_Id(data.person_Id);
self.firstName(data.firstName);
self.lastName(data.lastName);
self.age(data.age);
self.role(data.role);
};
};
和收藏
var PersonCollection = function () {
var self = this;
self.ItemToEditOrToAdd = ko.observable(new Person());
self.persons = ko.observableArray();
self.AddItem = function (item) {
self.persons.push(item);
};
};
和html
<div id="new" data-bind="with: PersonCollectionInstance.ItemToEditOrToAdd">
<p>Firstname: <input type="text" data-bind="value: firstName"/></p>
<p>Lastname: <input type="text" data-bind="value: lastName"/></p>
<p>Age: <input type="text" data-bind="value: age"/></p>
<p>Role: <input type="text" data-bind="value: role"/></p>
<button data-bind="click: $parent.PersonCollectionInstance.AddItem">Add new</button>
</div>
如果您查看 html,访问 AddItem 的自然方法是编写
<button data-bind="click: $parent.AddItem">Add new</button>
这不起作用,因为 $parent 绑定将我带到我的 AppVM,这是我的所有强大的视图模型,而不是回到我的 PersonCollectionInstance。
这就是为什么我需要这样做:
<button data-bind="click: $parent.PersonCollectionInstance.AddItem">Add new</button>
谁能向我解释为什么 $parent 让我回到我所有强大的视图模型而不是我的 AddItem 所在的 PersonCollectionInstance ?