コードが何をしようとしているのかは明確ではありません。2つの別々のビューモデルがあり、それらを相互に作用させたいようです。その場合は、おそらくポストボックスを使用することをお勧めします。これにより、ビューモデルを分離したまま、相互に通信できるようになります。
そのため、選択したタイトルを取得して、ビューモデルで新しいアイテムまたは子アイテムを作成するときに使用します。
邪魔にならないようにするにはtitle
、アイテムにプロパティを追加する必要があります。アイテムを、observableを持つ別のオブジェクトにマップします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());
私はあなたのフィドルを更新して、あなたがおそらく何をすべきかを示しました。