diff --git a/lib/gatejs.js b/lib/gatejs.js index c1a8a8b..6328d8f 100644 --- a/lib/gatejs.js +++ b/lib/gatejs.js @@ -10,14 +10,14 @@ module.exports = function () { var count = 0; - var completion = null; + var callbacks = []; return { enter: enter, exit: exit, close: close }; // enter the gate. // returns true if entrance is allowed. function enter() { - if (!completion) { + if (!callbacks.length) { count++; return true; } @@ -30,21 +30,21 @@ module.exports = function () { throw new Error('exit called while nobody was inside'); } if (!(--count)) { - if (completion) { - completion(); - } + _completion(); } } // trigger gate closing. function close(callback) { - if (completion) { - throw new Error('close was called more than once'); - } - callback = callback || function () { }; - completion = callback; + callbacks.push(callback || function() {}); if (!count) { - completion(); + _completion(); + } + } + + function _completion() { + if (callbacks.length) { + callbacks.forEach(function(cb){ cb(); }); } } } diff --git a/package.json b/package.json index efd2eb1..892773e 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,7 @@ "main": "./main", "bin": {}, "author": "yosefd ", - "version": "0.2.3", + "version": "0.2.4", "license": "MIT", "contributors": [ "Yosef Dinerstein " @@ -14,7 +14,7 @@ "gate" ], "engines": { - "node": "~0.6.x" + "node": "~0.10.x" }, "devDependencies": { "nodeunit": "0.6.x" diff --git a/test/gatetest.js b/test/gatetest.js index 23363ce..7c50632 100644 --- a/test/gatetest.js +++ b/test/gatetest.js @@ -3,12 +3,13 @@ var gate = require('../main').gate; module.exports = testCase({ - enterecloseexit: function (test) { + // close once + test1: function (test) { var gate1 = gate(); var step = 0; test.ok(gate1.enter(), 'should be able enter empty gate'); gate1.close(function () { - test.equal(step, 1, 'get clouse completion should come after everybody left'); + test.equal(step, 1, 'get close completion should come after everybody left'); step++; }); test.equal(step, 0, 'gate is not closed when somebody inside'); @@ -17,5 +18,27 @@ module.exports = testCase({ gate1.exit(); test.equal(step, 2, 'after everybody left, the gate is closed'); test.done(); + }, + + // close twice + test2: function (test) { + var gate1 = gate(); + var step = 0; + test.ok(gate1.enter(), 'should be able enter empty gate'); + gate1.close(function () { + test.equal(step, 1, 'get close completion should come after everybody left'); + step++; + }); + // close again + gate1.close(function () { + test.equal(step, 2, 'get cluse completion should come after everybody left'); + step++; + }); + test.equal(step, 0, 'gate is not closed when somebody inside'); + test.ok(!gate1.enter(), 'should not be able to enter into closing gate'); + step++; + gate1.exit(); + test.equal(step, 3, 'after everybody left, the gate is closed'); + test.done(); } }); \ No newline at end of file