Last active
December 18, 2015 05:19
-
-
Save cuth/5731924 to your computer and use it in GitHub Desktop.
Add this event handler to any class to give you the ability to trigger and bind events.
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
(function (exports) { | |
"use strict"; | |
exports.EventHandler = function () { | |
this.collection = {}; | |
}; | |
exports.EventHandler.prototype.bind = function (events, callback) { | |
var names = events.split(" "), | |
x, xlen = names.length; | |
for (x = 0; x < xlen; x += 1) { | |
if (typeof this.collection[names[x]] !== 'object') { | |
this.collection[names[x]] = []; | |
} | |
this.collection[names[x]].push(callback); | |
} | |
}; | |
exports.EventHandler.prototype.trigger = function (name) { | |
var names = name.split(":"), | |
args = Array.prototype.slice.call(arguments, 1), | |
i, ilen = names.length, | |
pieceName = "", | |
events, x, xlen; | |
for (i = 0; i < ilen; i += 1) { | |
pieceName += names[i]; | |
events = this.collection[pieceName]; | |
if (typeof events === 'object') { | |
xlen = events.length; | |
for (x = 0; x < xlen; x += 1) { | |
if (typeof events[x] === 'function') { | |
events[x].apply(this, args); | |
} | |
} | |
} | |
pieceName += ":"; | |
} | |
}; | |
}(this)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment