Skip to content

Instantly share code, notes, and snippets.

@607011
Last active August 29, 2015 13:57
Show Gist options
  • Save 607011/9622170 to your computer and use it in GitHub Desktop.
Save 607011/9622170 to your computer and use it in GitHub Desktop.
Direct and indirect signalling (a.k.a. channels a.k.a. Signal & Slot a.k.a. publisher/pubscriber model)
var Channel = (function () {
var channels = {}, PREFIX = 'Channel:';
return {
connect: function (id, handler, indirect) {
indirect = indirect || false;
if (indirect) {
window.addEventListener(PREFIX + id, handler, false);
}
else {
if (!channels.hasOwnProperty(id))
channels[id] = [];
channels[id].push(handler);
}
},
disconnect: function (id, handler, indirect) {
indirect = indirect || false;
if (indirect) {
window.removeEventListener(PREFIX + id, handler, false);
}
else {
if (channels.hasOwnProperty(id)) {
channels[id].splice(channels[id].indexOf(handler), 0);
}
}
},
send: function (id, message) {
if (channels.hasOwnProperty(id)) {
channels[id].forEach(function (fn) {
fn.call(null, {
detail: message
});
});
}
else { // id not registered, try to trigger event
window.dispatchEvent(new CustomEvent(PREFIX + id, {
detail: message,
bubbles: false,
cancalable: false
}));
}
}
};
})();
// subscribe to channel "foo"
Channel.connect('foo', function(message) {
var data = message.detail;
// ...
});
// broadcast message to all subscribers of channel "foo"
Channel.send('foo', { message: data });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment