diff --git a/hooks.js b/hooks.js index c7fbec0..cd4e8de 100644 --- a/hooks.js +++ b/hooks.js @@ -158,6 +158,20 @@ module.exports = { } return this; }, + removePost: function (name, fnToRemove) { + var proto = this.prototype || this + , posts = proto._posts || (proto._posts || {}); + if (!posts[name]) return this; + if (arguments.length === 1) { + // Remove all post callbacks for hook `name` + posts[name].length = 0; + } else { + posts[name] = posts[name].filter( function (currFn) { + return currFn !== fnToRemove; + }); + } + return this; + }, _lazySetupHooks: function (proto, methodName, errorCb) { if ('undefined' === typeof proto[methodName].numAsyncPres) { this.hook(methodName, proto[methodName], errorCb); diff --git a/test.js b/test.js index ef01b88..d542b1e 100644 --- a/test.js +++ b/test.js @@ -626,6 +626,52 @@ module.exports = { should.strictEqual(undefined, a.preValueOne); should.strictEqual(undefined, a.preValueTwo); }, + + 'should be able to remove a particular post': function () { + var A = function () {} + , postTwo; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + A.post('save', function (next) { + this.postValueOne = 2; + next(); + }); + A.post('save', postTwo = function (next) { + this.postValueTwo = 4; + next(); + }); + A.removePost('save', postTwo); + var a = new A(); + a.save(); + a.value.should.equal(1); + a.postValueOne.should.equal(2); + should.strictEqual(undefined, a.postValueTwo); + }, + + 'should be able to remove all posts associated with a hook': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + A.post('save', function (next) { + this.postValueOne = 2; + next(); + }); + A.post('save', function (next) { + this.postValueTwo = 4; + next(); + }); + A.removePost('save'); + var a = new A(); + a.save(); + a.value.should.equal(1); + should.strictEqual(undefined, a.postValueOne); + should.strictEqual(undefined, a.postValueTwo); + }, + '#pre should lazily make a method hookable': function () { var A = function () {};