Last active
December 23, 2015 14:19
-
-
Save danimal141/6647900 to your computer and use it in GitHub Desktop.
register and trigger events by eventuality function
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
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