Simple JavaScript Hook System

HTML
<p> <button onclick="on('click',function(){alert('hook `'+(new Date()).getTime()+'` added!')});">Add a <code>click</code> Hook</button> <button onclick="on('click.foo',function(){alert('hook `click.foo` added!')});">Add a <code>click</code> Hook with ID <code>foo</code></button> </p> <p> <button onclick="off('click');">Remove All <code>click</code> Hooks</button> <button onclick="off('click.foo');">Remove a <code>click</code> Hook with ID <code>foo</code></button> </p> <p> <button onclick="trigger('click');">Trigger All <code>click</code> Hooks</button> <button onclick="trigger('click.foo');">Trigger <code>click</code> Hook with ID `foo`</button> </p>
CSS
JAVASCRIPT
var hooks = {}; 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 (!name) { 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); } } }
Expand for more options Login