Last active
June 1, 2017 22:10
-
-
Save positlabs/7646311 to your computer and use it in GitHub Desktop.
Event broadcasting that follows the on / off / trigger pattern
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
/** | |
Event broadcasting that follows the on / off / trigger pattern | |
@arg obj: optional object to extend with events. NOTE: this event system only listens to events sent with .trigger. | |
dom events will not be listened for. To avoid confusion, you probably shouldn't use this on dom elements. | |
var e = new Events(); | |
e.on("eventname", callbackFunc); // add event listener | |
e.off("eventname", callbackFunc); // rm event listener | |
e.off("eventname") // rm all event listeners | |
e.trigger("eventname", data); // trigger an event, passing data arg to all subscribed listeners | |
// for convenience, you can keep reference to anonymous callback functions | |
var cb = e.on("eventname", function(){...}) | |
*/ | |
Events = function (obj) { | |
var events = obj || {}, // events object. new or existing | |
listeners = {}; // keeps arrays of functions with a notification key | |
events.debugEvents = false; | |
events.on = function (event, callback) { | |
if(events.debugEvents) console.log("Events."+"on()", arguments); | |
// event will be the key that we retrieve the array of callbacks with | |
if (listeners[event] == undefined) listeners[event] = []; | |
// add to the beginning of the array so they'll be in order when we do a reverse while loop to process them | |
listeners[event].unshift(callback); | |
return callback; | |
}; | |
events.off = function (event, callback) { | |
if(events.debugEvents) console.log("Events."+"off()", arguments); | |
try { | |
if (callback != undefined) { | |
// remove the callback | |
var callbacks = listeners[event]; | |
var callbackIndex = callbacks.indexOf(callback); | |
listeners[event].splice(callbackIndex, 1); | |
} else { | |
// remove all callbacks | |
listeners[event] = undefined; | |
} | |
} catch (e) { | |
// fail silently | |
} | |
}; | |
events.trigger = function (event, data) { | |
if(events.debugEvents) console.log("Events.trigger", event); | |
var callbacks = listeners[event] || []; | |
var i = callbacks.length; | |
while (i--) { | |
callbacks[i](data); | |
} | |
}; | |
return events; | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment