-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcallback.js
40 lines (33 loc) · 906 Bytes
/
callback.js
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
"use strict";
// Callback is a class (use with new) that stores functions to call
// back later, and they're called with a specified object.
function Callback() {
this.handlers = []; // observers
}
Callback.prototype = {
subscribe: function(fn) {
this.handlers.push(fn);
},
unsubscribe: function(fn) {
this.handlers = this.handlers.filter(
function(item) {
if (item !== fn) {
return item;
}
}
);
},
fire: function(o, thisObj) {
// TODO: Put error handling around the call?
this.handlers.forEach(function(item) {
try {
item.call(thisObj, o);
} catch (err) {
console.log('Ignored error calling back ', item.name, 'with', o, '-', err);
}
});
}
}
module.exports = {
Callback
};