diff --git a/lib/Event.js b/lib/Event.js index 726e777..08d92b4 100644 --- a/lib/Event.js +++ b/lib/Event.js @@ -3,8 +3,9 @@ var sinon = require('sinon'); module.exports = Event; function Event() { - this.listeners = []; - this.addListener = sinon.spy(this.addListener.bind(this)); + this.listeners = []; + this.addListener = sinon.spy(this.addListener.bind(this)); + this.removeListener = sinon.spy(this.removeListener.bind(this)); } /** @@ -20,6 +21,17 @@ Event.prototype.addListener = function (fn) { this.listeners.push(fn); }; +/** + * Remove an event handler function + * @param {function} fn + */ +Event.prototype.removeListener = function (fn) { + var index = this.listeners.indexOf(fn); + if (index > -1) { + this.listeners.splice(index, 1); + } +}; + /** * Trigger event * @param {...object} arg diff --git a/test/unit/lib/Event.spec.js b/test/unit/lib/Event.spec.js index a75f476..cedbe11 100644 --- a/test/unit/lib/Event.spec.js +++ b/test/unit/lib/Event.spec.js @@ -1,15 +1,16 @@ var Event = hmt.lib('Event'); describe('Event', function () { - var event; - before(function () { - event = new Event(); - }); describe('addListener', function () { var fn; var result; + var event; + + before(function () { + event = new Event(); + }); before(function () { fn = function (name) { @@ -32,4 +33,42 @@ describe('Event', function () { hmt.assert.equal(result, 'hi seth'); }); }); + + describe('removeListener', function () { + var fn; + var result; + var event; + + before(function () { + event = new Event(); + fn1 = hmt.spy(function Hello (name) { + result = 'hi ' + name; + }); + + fn2 = hmt.spy(function Bye (name) { + result = 'goodbye, ' + name; + }); + + event.addListener(fn2); + event.addListener(fn1); + event.removeListener(fn1); + }); + + it('should be a spy', function () { + hmt.assert.equal(event.removeListener.callCount, 1); + }); + + it('should only have recorded the functions that are still being listened to', function () { + hmt.assert.equal(event.listeners.length, 1); + hmt.assert.equal(event.listeners.indexOf(fn1), -1); + hmt.assert.equal(event.listeners.indexOf(fn2) > -1, true); + }); + + it('should not call the function that is no longer being listened to', function () { + event.trigger('mark'); + hmt.assert.equal(result, 'goodbye, mark'); + hmt.assert.equal(fn1.callCount, 0); + hmt.assert.equal(fn2.callCount, 1); + }); + }); });