Skip to content

Instantly share code, notes, and snippets.

@danimal141
Last active December 23, 2015 14:19
Show Gist options
  • Save danimal141/6647900 to your computer and use it in GitHub Desktop.
Save danimal141/6647900 to your computer and use it in GitHub Desktop.
register and trigger events by eventuality function
var eventuality = function(that){
var registry = {};
that.on = function(type, method, parameters){
var handler = {
method : method,
parameters : parameters
};
if(registry.hasOwnProperty(type)){
registry[type].push(handler);
}else{
registry[type] = [handler];
}
return this;
};
that.trigger = function(event){
var array,
func,
handler,
i,
type = typeof event === "string" ? event : event.type;
if(registry.hasOwnProperty(type)){
array = registry[type];
for(i = 0; i < array.length; i++){
handler = array[i];
func = handler.method;
if(typeof func === "string"){
func = this[func];
}
func.apply(this, handler.parameters || [event]);
}
}
return this;
};
// that.get_registry = function(){
// return registry;
// };
return that;
};
//example
var obj = {};
eventuality(obj);
obj.on("click", function(){
alert("clicked!!");
});
obj.on("touch", function(){
alert("Don't touch me!!");
})
obj.trigger("click").trigger("touch");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment