-
Notifications
You must be signed in to change notification settings - Fork 2
/
EventBus.js
72 lines (71 loc) · 2.08 KB
/
EventBus.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
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
var EventBusClass = {};
EventBusClass = function() {
this.listeners = {};
};
EventBusClass.prototype = {
addEventListener:function(type, callback, scope) {
var args = [];
var numOfArgs = arguments.length;
for(var i=0; i<numOfArgs; i++){
args.push(arguments[i]);
}
args = args.length > 3 ? args.splice(3, args.length-1) : [];
if(typeof this.listeners[type] != "undefined") {
this.listeners[type].push({scope:scope, callback:callback, args:args});
} else {
this.listeners[type] = [{scope:scope, callback:callback, args:args}];
}
},
removeEventListener:function(type, callback, scope) {
if(typeof this.listeners[type] != "undefined") {
var numOfCallbacks = this.listeners[type].length;
var newArray = [];
for(var i=0; i<numOfCallbacks; i++) {
var listener = this.listeners[type][i];
if(listener.scope == scope && listener.callback == callback) {
} else {
newArray.push(listener);
}
}
this.listeners[type] = newArray;
}
},
dispatch:function(type, target) {
var numOfListeners = 0;
var event = {
type:type,
target:target
};
var args = [];
var numOfArgs = arguments.length;
for(var i=0; i<numOfArgs; i++){
args.push(arguments[i]);
};
args = args.length > 2 ? args.splice(2, args.length-1) : [];
args = [event].concat(args);
if(typeof this.listeners[type] != "undefined") {
var numOfCallbacks = this.listeners[type].length;
for(var i=0; i<numOfCallbacks; i++) {
var listener = this.listeners[type][i];
if(listener && listener.callback) {
listener.args = args.concat(listener.args);
listener.callback.apply(listener.scope, listener.args);
numOfListeners += 1;
}
}
}
},
getEvents:function() {
var str = "";
for(var type in this.listeners) {
var numOfCallbacks = this.listeners[type].length;
for(var i=0; i<numOfCallbacks; i++) {
var listener = this.listeners[type][i];
str += listener.scope && listener.scope.className ? listener.scope.className : "anonymous";
str += " listen for '" + type + "'\n";
}
}
return str;
}
};
var EventBus = new EventBusClass();