Skip to content

Instantly share code, notes, and snippets.

@sliwey-zz
Last active November 3, 2017 07:30
Show Gist options
  • Save sliwey-zz/59e3fd60aac9ddf860242fcd593fc78f to your computer and use it in GitHub Desktop.
Save sliwey-zz/59e3fd60aac9ddf860242fcd593fc78f to your computer and use it in GitHub Desktop.
pub/sub
var Events = (function() {
var listen,
trigger,
remove,
once,
clientMap = {};
listen = function(key, fn) {
(clientMap[key] || (clientMap[key] = [])).push(fn);
}
trigger = function() {
var key = Array.prototype.shift.apply(arguments);
var clients = clientMap[key] || [];
if (clients.length === 0) {
return;
}
for (var i = 0; i < clients.length; i++) {
clients[i].apply(this, arguments);
}
}
remove = function(key, fn) {
if (arguments.length === 0) {
clientMap = {};
return;
}
if (!fn) {
clientMap[key] = [];
return;
}
var clients = clientMap[key];
for (var i = 0; i < clients.length; i++) {
if (clients[i] === fn || clients[i].fn === fn) {
clients.splice(i, 1);
break;
}
}
}
once = function(key, fn) {
function one () {
fn.apply(this, arguments);
this.remove(key, one);
}
one.fn = fn;
this.listen(key, one);
}
return {
listen: listen,
trigger: trigger,
once: once,
remove: remove
}
})();
function cb1(data) {
console.log('login1:', data);
}
Events.listen('login', cb1);
Events.listen('login', function(data) {
console.log('login2:', data);
});
Events.listen('login2', function(data) {
console.log('login2:', data);
});
// Events.remove('login', cb1);
function cb2(data) {
console.log('once:', data);
}
// Events.once('login', cb2);
// Events.remove('login', cb2);
Events.remove()
Events.trigger('login', {status: 'success'});
Events.trigger('login2', {status: 'success2'});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment