目前還不清楚你的代碼試圖做什麼。看起來你有兩個獨立的視圖模型,你希望他們互相交互。如果是這種情況,您可能需要使用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);
}));
}
我認爲最簡單的方法是創建一個「添加」和「的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證明你或許應該做的事情。
不幸的是,這不是真的有幫助。它不會將選定的標題與您添加的項目相關聯。該名稱顯示在視圖上,但如果再次呈現視圖,則會全部丟失。 –