我正在关注这个帖子:
http://www.knockmeout.net/2012/05/using-ko-native-pubsub.html
允许我的一个虚拟机与另一个虚拟机通信。我的一个 viewModel 有一个数组,我需要将其公开给另一个 viewModel。如果此数组不是可观察的,则上述帖子中的方法可以正常工作。
如果数组是可观察数组,则从不填充 publishedSelectedFolders。我试图找出原因;希望这是我正在做的愚蠢的事情。
这是我的jsFiddle:
如果您在 vm 中取消注释该行,它会按预期工作(在勾选检查时填充publishedSelectedFolders)。为什么会这样?
代码:
/*
* Pub/Sub (decouples VMs but lets them access each others' data)
*/
var postbox = new ko.subscribable();
ko.subscribable.fn.publishOn = function (topic) {
this.subscribe(function (newValue) {
postbox.notifySubscribers(newValue, topic);
});
return this; //support chaining
};
ko.subscribable.fn.subscribeTo = function (topic) {
postbox.subscribe(this, null, topic);
return this; //support chaining
};
/* Selection code */
this.publishedSelectedFolders = ko.observableArray().subscribeTo("SELECTED_FOLDERS");
var vm = {
folders: ko.observableArray([{
"folderId": "1"
}, {
"folderId": "2"
}]),
// folders: [{"folderId": "1"}, {"folderId": "2"}, {"folderId": "3"}],
selectedFolderIds: ko.observableArray(),
};
vm.folderIndex = {};
ko.utils.arrayForEach(vm.folders, function (folder) {
vm.folderIndex[folder.folderId] = folder;
});
/* monitors selections and publishes to the shell */
this.selectedFolders = ko.computed(function () {
return ko.utils.arrayMap(vm.selectedFolderIds(), function (id) {
return vm.folderIndex[id];
});
}).publishOn("SELECTED_FOLDERS");
ko.applyBindings(vm);