From 567cc6730d8627a5eeff57b0e51b42afbf416caf Mon Sep 17 00:00:00 2001 From: indexzero Date: Wed, 22 Jul 2015 00:05:28 -0700 Subject: [PATCH 1/2] [refactor] Simplify `registrar` function. --- index.js | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/index.js b/index.js index dfaa0fe..5abaa80 100644 --- a/index.js +++ b/index.js @@ -22,20 +22,19 @@ function Understudy() { function registrar(property) { return function (action, callback) { - if (typeof action === 'string') { - if (typeof callback === 'function') { - this[property] || (this[property] = {}); - this[property][action] || (this[property][action] = []); - var interceptors = this[property][action]; - interceptors[interceptors.length] = callback; - return this; - } - else { - throw new Error('callback must be a function'); - } + if (typeof action !== 'string') { + throw new Error('event must be a string'); + } else if (typeof callback !== 'function') { + throw new Error('callback must be a function'); } - throw new Error('event must be a string'); - } + + this[property] = this[property] || {}; + var interceptors = this[property][action] + = this[property][action] || []; + + interceptors.push(callback); + return this; + }; } function perform(action /* , args..., performFn, callback*/) { From b7b49ce8ab8e1667debe2206b064f4d37bdece91 Mon Sep 17 00:00:00 2001 From: indexzero Date: Wed, 22 Jul 2015 01:38:12 -0700 Subject: [PATCH 2/2] [api] Expose the registrar function and allow for `unshift` as well as `push`. --- index.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index 5abaa80..0470853 100644 --- a/index.js +++ b/index.js @@ -17,10 +17,13 @@ function Understudy() { this.before = registrar('_before_interceptors'); this._before_interceptors = null; this._after_interceptors = null; + this._interceptor_registrar = registrar; return this; } -function registrar(property) { +function registrar(property, fn) { + fn = fn || 'push'; + return function (action, callback) { if (typeof action !== 'string') { throw new Error('event must be a string'); @@ -32,7 +35,7 @@ function registrar(property) { var interceptors = this[property][action] = this[property][action] || []; - interceptors.push(callback); + interceptors[fn](callback); return this; }; }