knockout.js - Knockout components communication -
knockout.js - Knockout components communication -
i have web app want convert , spa using ko components. wonder how kind of inter component communication.
for illustration want "notification" component in every single component can send notifications.
i managed find solution sharing observable array in main view model:
var vm = function() { var self = this; this._notifications = ko.observablearray([]); this.notifications = { addinfo: function(text){ self._notifications.push(text); } } } and
<comp1 params="{app: $data}"></comp1><br/> <comp2 params="{app: $data}"></comp2><br/> <notif params="{app: $data}"></notif> see here: http://jsfiddle.net/nveron/j4829y7p/
i'm not satisfied solution, rather have kept notification info in notify component.
do have thought deal that?
you can utilize ko.subscribable implement simple pub/sub message bus:
ko.subscribable.subscribe subscribe new messages ko.subscribable.notifysubscribers publish new messages
more in this article ryan niemeyer.
in case, can create global postbox object based on ko.subscribable. componenents publish messages in , notification vm subscribes it.
you can publish , subscribe message topic.
demo: jsfiddle
var postbox = (function() { var pb = new ko.subscribable(); homecoming { subscribe: function(handler, topic) { pb.subscribe(handler, null, topic) }, publish: function(message, topic) { pb.notifysubscribers(message, topic); } }; }()); a component: var comp1 = function(params) { this.addtonotif = function(){ postbox.publish("comp1 here"); } } notif: ... postbox.subscribe(function(message) { self.notifs.push(message); }); knockout.js single-page-application knockout-components
Comments
Post a Comment