Created
May 12, 2014 22:18
-
-
Save maruf89/7ef52e239a6c53aa1e59 to your computer and use it in GitHub Desktop.
Borrowed from Contra and applied to an angular module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular.module('contra.eventEmitter', []) | |
.factory('eventEmitter', function () { | |
'use strict'; | |
return { | |
emitter: function (thing) { | |
var evt = {}, | |
tick = function tick (fn) { setTimeout(fn, 0); }, | |
debounce = function (fn, args) { if (!fn) { return; } tick(function run () { fn.apply(null, args || []); }); } | |
if (thing === undefined) { thing = {}; } | |
thing.on = function (type, fn) { | |
if (!evt[type]) { | |
evt[type] = [fn]; | |
} else { | |
evt[type].push(fn); | |
} | |
}; | |
thing.once = function (type, fn) { | |
fn._once = true; // thing.off(fn) still works! | |
thing.on(type, fn); | |
}; | |
thing.off = function (type, fn) { | |
var et = evt[type]; | |
if (!et) { return; } | |
et.splice(et.indexOf(fn), 1); | |
}; | |
thing.emit = function () { | |
var args = Array.prototype.slice.call(arguments), | |
type = args.shift(), | |
et = evt[type]; | |
if (type === 'error' && !et) { throw args.length === 1 ? args[0] : args; } | |
if (!et) { return; } | |
evt[type] = et.filter(function emitter (listen) { | |
debounce(listen, args); | |
return !listen._once; | |
}); | |
}; | |
return thing; | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment