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 postboxinstance is one and the same instance being shared between both viewmodels and that the notifySubscribersand 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();
function MyModalViewA()
{
var _self = this;
_self.rows = ko.observableArray([
{ label: "foo" },
{ label: "bar" }
]);
postbox.subscribe(function(newValue) {
_self.rows.push(newValue);
}, null, "PFX.NewRowAvailable"
);
};
function MyModalViewB()
{
var _self = this;
_self.search = function() {
var newRow = { "label" : "baz" };
postbox.notifySubscribers(newRow, "PFX.NewRowAvailable");
};
};
var vma = new MyModalViewA();
ko.applyBindings(vma, $("#vma").get(0));
var vmb = new MyModalViewB();
ko.applyBindings(vmb, $("#vmb").get(0));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div id="vma">
<h3>ViewModel A</h3>
<ol data-bind="foreach: rows">
<li data-bind="text: label"></li>
</ol>
</div>
<hr />
<div id="vmb">
<h3>ViewModel B</h3>
<button data-bind="click: search">search</button>
</div>
Post a Comment for "Knockoutjs And Pubsub To Update Observable Array Between Views"