Reputation: 12915
I'm following RN's blog post here about pub/sub synchronization:
http://www.knockmeout.net/2012/05/using-ko-native-pubsub.html
My application has a 'shell' viewModel with various internal viewModels, one of which being 'folder'. Within the folder viewmodel, I list folders.
From the shell's menu bar, I need to be able to add another folder. This is the way I'm achieving it right now:
In shell.js:
this.clickedAddFolder = ko.observable(false).publishOn("CLICKED_ADD_FOLDER");
this.addFolder = function () { clickedAddFolder(true); clickedAddFolder(false); };
Then in folder.js:
var clickedAddFolder = ko.observable().subscribeTo("CLICKED_ADD_FOLDER");
innerModel.addFolder = ko.computed(function() {
if (clickedAddFolder()) {
var folder = new folderViewModel(addFolderDto);
innerModel.folders.push(folder);
refreshIsotope();
}
}).bind(this);
The idea is that shell.js will quickly toggle the clicked_add_folder property, which folder.js has subscribed to. A computed observable detects this change and triggers some function - adding a folder. Is this a reasonable solution? I'd like to avoid finding a solution that "works"; I want to learn how to properly achieve this result.
Upvotes: 2
Views: 1624
Reputation: 3167
I'm assuming you're using ko.postbox
? If that is the case, I would think it'd be a bit cleaner if you just dropped the observables and publish/subscribe directly to the topic like so:
// shell.js
this.addFolder = function addFolder(e) {
// 'Add Folder' clicked, publish on the topic
ko.postbox.publish('CLICKED_ADD_FOLDER', e);
};
//folder.js
ko.postbox.subscribe('CLICKED_ADD_FOLDER', function onClickedAddFolder(e) {
var folder = new folderViewModel(addFolderDto);
innerModel.folders.push(folder);
refreshIsotope();
});
Here's a JSFiddle without actually loading postbox, but I basically just ripped out the two necessary functions from postbox: http://jsfiddle.net/QqBhk/
Upvotes: 3