问题描述
我正在关注该帖子:
http://www.knockmeout.net/2012/05/using-ko-native-pubsub.html
允许我的一个虚拟机与另一个虚拟机通信.我的一个viewModels有一个数组,我需要将该数组公开给另一个viewModel.如果该数组不是可观察到的,则上述文章中的方法就可以正常工作.
to allow one of my vms to communicate with the other. One of my viewModels has an array that I need to expose to another viewModel. If this array is not an observable, the method from the above post works just fine.
如果该数组是可观察的数组,则永远不会填充publishedSelectedFolders.我试图找出原因;希望这是我正在做的愚蠢的事情.
If the array is an observable array, publishedSelectedFolders is never populated. I'm trying to figure out why; hopefully it's something silly I'm doing.
这是我的jsFiddle:
Here's my jsFiddle:
如果在虚拟机中取消注释该行,则该行将按预期工作(在勾选了勾号的情况下,将填充publishedSelectedFolders).为什么会这样?
If you uncomment the line in the vm, it works as expected (publishedSelectedFolders is populated as checks are ticked). Why is this happening?
代码:
/*
* 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);
推荐答案
ko.utils.array...
助手不要自动解包可观察对象(请参见 github上的源代码).因此,您需要将已经解开的数组传递给它们,而不是直接传递observableArray
.
The ko.utils.array...
helpers do not unwrap observables automatically (see source on github). So you need to pass them the already unwrapped arrays and not the observableArray
directly.
因此错误发生在您的arrayForEach
呼叫中,正确的用法是:
So the error is in your arrayForEach
call, where the correct usage is:
ko.utils.arrayForEach(viewModel.documents(), function(doc) {
viewModel.documentIndex[doc.documentId] = doc;
});
请注意viewModel.documents()
末尾的()
,以及如何正确使用ko.utils.arrayMap
中的viewModel.selectedDocumentIds()
.
note the ()
at the end of the viewModel.documents()
, and how you have used correctly the viewModel.selectedDocumentIds()
in the ko.utils.arrayMap
.
您固定的 JSFiddle .
这篇关于具有剔除发布/订阅的可观察数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!