File size: 1,970 Bytes
5fae594
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
'use strict';

var should = require('should');
var Callbacks = require('../../source/callbacks');

var namespace = {
  reset: function () {
    namespace.listeners = {};
  },
  listeners: {},
  once: function (event, fn) {
    if (! namespace.listeners[event]) {
      namespace.listeners[event] = [];
    }
    namespace.listeners[event].push(fn);
  }
};

describe('Callbacks', function () {

  beforeEach(function() {
    namespace.reset();
  });

  describe(':constructor', function () {

    it('should create a new callbacks instance', function () {
      var callbacks = new Callbacks(namespace);
      callbacks.should.have.keys('collection', 'index', 'namespace');
    });

  });

  describe(':register', function () {

    it('should register a new callback', function (done) {
      var callbacks = new Callbacks(namespace);

      var fn = function (a, b, c) {
        arguments.should.eql([1,2,3]);
        done();
      };

      var id = callbacks.register(fn);

      id.should.be.have.type('number');
      callbacks.collection.should.keys(id.toString());
      callbacks.index.should.equal(id + 1);

      var listener = namespace.listeners['fn_' + id];
      listener.should.have.length(1);
      listener[0].should.have.type('function');
      listener[0](1, 2, 3);
    });

  });

  describe(':exec', function () {

    it('should execute a callback', function (done) {
      var callbacks = new Callbacks(namespace);

      var fn = function (a, b, c) {
        arguments.should.eql([1, 2, 3]);
        done();
      };

      var id = callbacks.register(fn);

      callbacks.exec(id, 1, 2, 3);
    });

    it('should only execute a callback once', function (done) {
      var callbacks = new Callbacks(namespace);

      var fn = function (x) {
        x.should.equal(1);
        done();
      };

      var id = callbacks.register(fn);

      callbacks.exec(id, 1);
      callbacks.exec(id, 2);
      callbacks.exec(id, 3);

    });

  });

});