Skip to content

Instantly share code, notes, and snippets.

@michaelhue
Last active February 21, 2016 22:53
Show Gist options
  • Save michaelhue/b3332710b1181f37f9df to your computer and use it in GitHub Desktop.
Save michaelhue/b3332710b1181f37f9df to your computer and use it in GitHub Desktop.
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