var hooks = {}; // store all hooks here
function on(name, fn) {
name = name.split('.');
if (!hooks[name[0]]) hooks[name[0]] = {};
var i = name[1] || Object.keys(hooks[name[0]]).length;
hooks[name[0]][i] = fn;
}
function off(name) {
if (typeof name === "undefined") {
return hooks = {};
}
name = name.split('.');
if (name[1]) {
delete hooks[name[0]][name[1]];
} else {
delete hooks[name[0]];
}
}
function trigger(name, param) {
name = name.split('.');
if (!hooks[name[0]]) hooks[name[0]] = {};
if (name[1]) {
if (hooks[name[0]][name[1]]) hooks[name[0]][name[1]].apply({}, param);
} else {
for (var i in hooks[name[0]]) {
hooks[name[0]][i].apply({}, param);
}
}
}
/*
// add a `click` hook
on("click", function(x) {
alert('test ' + x + ' ok!');
});
// add a `click` hook with `foo` namespace
on("click.foo", function(x) {
alert('test ' + x + ' foo ok!');
});
// remove all `click` hooks
off("click");
// remove `click.foo` hook only
off("click.foo");
// trigger all `click` hooks
trigger("click", ['this will be the `x`', 'this will be the second function parameter…']);
// trigger `click.foo` hook only
trigger("click.foo", ['this will be the `x`', 'this will be the second function parameter…']);
*/
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.