JSFiddle - React, Tailwind, and code Playground
HTML
<script src="http://knockoutjs.com/downloads/knockout-3.2.0.js"></script>
<comp1></comp1><br/>
<comp2></comp2><br/>
<notif></notif>
JavaScript
var postbox = (function() {
var pb = new ko.subscribable();
return {
subscribe: function(handler, topic) {
pb.subscribe(handler, null, topic)
},
publish: function(message, topic) {
pb.notifySubscribers(message, topic);
}
};
}());
var comp1 = function(params) {
this.addToNotif = function(){
postbox.publish("comp1 was here");
}
}
var comp2 = function(params) {
this.addToNotif = function(){
postbox.publish("comp2 also");
}
}
var notif = function(params){
var self = this;
this.notifs = ko.observableArray();
postbox.subscribe(function(message)
self.notifs.push(message);
});
}
var comp1VM = { viewModel: comp1, template: '<button data-bind="click:addToNotif">Add notification from comp1</button>' };
var comp2VM = { viewModel: comp2, template: '<button data-bind="click:addToNotif">Add notification from comp2</button>' };
var notifVM = { viewModel: notif, template: '<ul data-bind="foreach: notifs"><li data-bind="text: $data"></li></ul>' };
ko.components.register('comp1', comp1VM);
ko.components.register('comp2', comp2VM);
ko.components.register('notif', notifVM);
ko.applyBindings();