File size: 1,347 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 |
'use strict';
/*
* Constants
*/
var PREFIX = 'fn_';
/*
* Callbacks Constructor
*/
var Callbacks = function Callbacks (namespace) {
this.collection = {};
this.index = 0;
this.namespace = namespace;
};
/*
* Register
*
* - fn (function) : the callback
* > callback id (int)
*/
Callbacks.prototype.register = function register (fn) {
var self = this;
var id = this.index++;
this.collection[id] = fn;
this.namespace.once(PREFIX + id, function callbackListener (arg1, arg2, arg3) {
self.exec(id, arg1, arg2, arg3);
});
return id;
};
/*
* Exec
* Deletes the callback afterwards so it can only be executed once.
*
* - id (int) : callback id
* - args (array) : arguments
*/
Callbacks.prototype.exec = function exec (id, arg1, arg2, arg3) {
if (! this.collection.hasOwnProperty(id)) return;
this.collection[id](arg1, arg2, arg3);
delete this.collection[id];
};
/*
* (Private) Get Fn
*
* - id (int) : the callback id
* > function
*/
Callbacks.prototype.getFn = function getFn (id) {
var self = this;
return function callback (arg1, arg2, arg3) {
self.namespace.emit(PREFIX + id, arg1, arg2, arg3);
};
};
/*
* Release
*/
Callbacks.prototype.release = function release () {
delete this.collection;
delete this.index;
delete this.namespace;
};
module.exports = Callbacks;
|