-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathEvents.js
More file actions
85 lines (75 loc) · 2.07 KB
/
Events.js
File metadata and controls
85 lines (75 loc) · 2.07 KB
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
/**
* @class Events
*
* @author Matteo Burgassi
*/
/*
onGoingNotification {
'event_name01': [
0 : {
callback: function(event) {}
context: object_or_class
}
1: ...
]
'event_name02': ...
}
*/
Refuel.define('Events',
function Events() {
if(this.notify && this.subscribe) return;
var onGoingNotification = {};
this.onGoingNotification = onGoingNotification;
this.notify = function(name, data, bubble){
if (!name || typeof(name)!=='string'){
throw new TypeError('Invalid event name ' + name);
}
data = data || {};
if (onGoingNotification[name] instanceof Array) {
var handlers = [].concat(onGoingNotification[name]);
for (var i = 0, handler; handler = handlers[i]; i++) {
handler.callback.call(handler.context, data);
}
}
}
this.subscribe = function(name, callback, context){
if (!name || typeof(name)!=='string'){
throw new TypeError('Invalid event name ' + name);
}
if (!callback || typeof(callback)!=='function'){
throw new TypeError('Invalid event callback ' + callback);
}
if (!context) context = this;
if (typeof onGoingNotification[name] === 'undefined') {
onGoingNotification[name] = [];
}
else {
//if the same callback is subscribed to the same event, remove it
this.unsubscribe(name, callback);
}
var handler = {
'callback': callback,
'context': context
}
onGoingNotification[name].push(handler);
}
this.isSubscribed = function(name) {
return !(Refuel.isUndefined(onGoingNotification[name]) || onGoingNotification[name].length===0);
}
this.unsubscribe = function(name, callback) {
if(!name || typeof name !== "string" || (callback && typeof callback !== "function")){
throw new TypeError("name is not defined or wrong callback");
}
if (callback) {
for (var i=0, l=onGoingNotification[name].length; i<l; i++) {
if(onGoingNotification[name][i].callback.toString() === callback.toString()){
onGoingNotification[name].splice(i, 1);
return;
}
}
}
else{
delete onGoingNotification[name];
}
}
});