Skip to content

Instantly share code, notes, and snippets.

@michaelhue michaelhue/hookify.js
Last active Feb 21, 2016

Embed
What would you like to do?
Hookify.js – a simple helper for implementing the Hooks pattern.
/**
* Hookify
*
* A very simple helper for implementing the Hooks pattern in your applications.
*
* @param {Object} obj The object containing hooks.
* @param {Object} ctx Optional context that is applied to hooks. Defaults to the obj.
* @return {Function}
*/
function hookify(obj, ctx) {
/**
* Fires a hook with optional arguments.
*
* @param {String} key Key of the hook to fire.
* @param {Mixed} ...args Arguments to pass to the hook.
* @return {Mixed} Returns the result of the hook or undefined.
*/
var hook = function() {
var key = arguments[0];
var args = Array.prototype.slice.call(arguments, 1);
if (typeof obj[key] !== 'function') {
return undefined;
}
return obj[key].apply((ctx || obj), args);
};
/**
* Check if the hook does not explicitly deny the action,
* i.e. does not return false.
*
* @param {String} key
* @param {Mixed} ...args
* @return {Boolean}
*/
hook.allows = function() {
return hook.apply(this, arguments) !== false;
};
/**
* Check if the hook explicitly denies the action,
* i.e. returns false.
*
* @param {String} key
* @param {Mixed} ...args
* @return {Boolean}
*/
hook.denies = function() {
return hook.apply(this, arguments) === false;
};
return hook;
}
// hookify.js
function hookify(n,r){var t=function(){var t=arguments[0],e=Array.prototype.slice.call(arguments,1);return"function"!=typeof n[t]?void 0:n[t].apply(r||n,e)};return t.allows=function(){return t.apply(t,arguments)!==!1},t.denies=function(){return t.apply(t,arguments)===!1},t}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.