Skip to content

Instantly share code, notes, and snippets.

@renzocastro
Last active April 2, 2018 14:34
Show Gist options
  • Save renzocastro/485c11b987a915af65541e353415b795 to your computer and use it in GitHub Desktop.
Save renzocastro/485c11b987a915af65541e353415b795 to your computer and use it in GitHub Desktop.
Basic emitter in JavaScript
// EXAMPLE 1
var formSended = new Signal();
formSended.add(function () { console.log('A'); });
formSended.add(function () { console.log('B'); });
// Put this anywhere in your code
formSended.dispatch();
// console output => 'A'
// console output => 'B'
// EXAMPLE 2
var signalWithParams = new Signal();
signalWithParams.add((a, b) => console.log(a + b));
// Put this anywhere in your code
signalWithParams.dispatch(2, 3);
// console output => 5
(function (global) {
var Signal = function () {
this._listeners = [];
};
Signal.prototype.constructor = Signal;
Signal.prototype.add = function (handler, priority) {
this._listeners.push({
handler: handler,
priority: (priority === undefined ? 0 : priority)
});
};
Signal.prototype.remove = function (handler) {
for (var i = this._listeners.length; i >= 0; --i) {
if (this._listeners[i].handler === handler) {
this._listeners.splice(i, 1);
}
}
};
Signal.prototype.removeAll = function () {
this._listeners = [];
};
Signal.prototype.dispatch = function () {
var args = Array.prototype.slice.call(arguments);
var sortDesc = function (a, b) {
return b.priority - a.priority;
};
this._listeners.sort(sortDesc).forEach(function (item) {
item.handler.apply(item.handler, args);
});
};
if (typeof define === 'function' && define.amd) { // AMD
define(function () { return Signal; });
} else if (typeof module !== 'undefined' && module.exports) { // node
module.exports = Signal;
} else { // browser
// use string because of Google closure compiler ADVANCED_MODE
global['Signal'] = Signal;
}
}(this));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment