Knockoutjs And Pubsub To Update Observable Array Between Views
I have two modalviews - MyModalViewA (parent) and MyModalViewB (child). MyModalViewA spawns MyModalViewB, as custom binding, as well has observable array which I need to update. An
Solution 1:
Make sure that the postbox
instance is one and the same instance being shared between both viewmodels and that the notifySubscribers
and subcribe
methods follow the signatures below.
notifySubscribers(eventData, eventName);
subscribe(function(eventData) { ... }, null, eventName);
Below you find a simplified version of what you are trying to achieve. Here only 1 search result is being passed, but it might also be more via eg. an array.
var postbox = ko.observable();
functionMyModalViewA()
{
var _self = this;
_self.rows = ko.observableArray([
{ label: "foo" },
{ label: "bar" }
]);
postbox.subscribe(function(newValue) {
_self.rows.push(newValue);
}, null, "PFX.NewRowAvailable"
);
};
functionMyModalViewB()
{
var _self = this;
_self.search = function() {
var newRow = { "label" : "baz" };
postbox.notifySubscribers(newRow, "PFX.NewRowAvailable");
};
};
var vma = newMyModalViewA();
ko.applyBindings(vma, $("#vma").get(0));
var vmb = newMyModalViewB();
ko.applyBindings(vmb, $("#vmb").get(0));
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script><divid="vma"><h3>ViewModel A</h3><oldata-bind="foreach: rows"><lidata-bind="text: label"></li></ol></div><hr /><divid="vmb"><h3>ViewModel B</h3><buttondata-bind="click: search">search</button></div>
Post a Comment for "Knockoutjs And Pubsub To Update Observable Array Between Views"