不清楚您的代码试图做什么。似乎您有两个独立的视图模型,并且您希望它们相互交互。如果是这种情况,您可能想使用postbox。它将允许您将视图模型分开,但仍允许它们相互通信。
因此,您希望获取选定的标题,并在视图模型中创建新项目或子项目时使用它。
只是为了让它不碍事,您确实需要为您的项目添加一个title 属性。将项目映射到另一个具有可观察到的 title 的对象。
function Item(data) {
var self = this;
self.title = ko.observable(data.title); // add a 'title' property to all items
self.name = ko.observable(data.name);
// map any existing child items to new Items
self.childItems = ko.observableArray(ko.utils.arrayMap(data.childitems, function (item) {
return new Item(item);
}));
}
我认为最简单的方法是创建一个“add”和“addChild”主题并让您的视图模型订阅它。当您获得该主题的更新时,您可以使用该标题添加新项目。然后从您的外部来源,让它发布您希望使用的标题到适当的主题。
function ViewModel(data) {
var self = this;
// ...
var i = 5;
function newItem(title) {
return new Item({
title: title,
name: i++,
childItems: []
});
}
ko.postbox.subscribe('add', function (title) {
// a title was received for the `add` topic, add it
self.items.push(newItem(title));
});
ko.postbox.subscribe('addChild', function (title) {
// a title was received for the `addChild` topic, add it
var firstItem = self.items()[0];
if (firstItem) {
firstItem.childItems.push(newItem(title));
}
});
}
// add a new item using the selected title
ko.postbox.publish('add', selectedTitle());
// add a new child item using the selected title
ko.postbox.publish('addChild', selectedTitle());
我updated your fiddle 来演示你可能应该做什么。