-
Notifications
You must be signed in to change notification settings - Fork 10
/
Event.js
123 lines (107 loc) · 3.05 KB
/
Event.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
/**
* @module NPMap.Event
*/
define(function() {
var
// Contains all of the active events.
activeEvents = [],
// An incrementing integer to use for event ids.
id = 0;
return NPMap.Event = {
/**
* Adds an event.
* @param {String} obj The name of the nested class, in "NPMap.ObjectName" format, to add the event to.
* @param {String} event The name of the event to add to the class.
* @param {Function} func The function to call when the event is fired.
* @param {Boolean} single (Optional) Should this event only be called once and then disposed?
* @return {Number}
*/
add: function(obj, event, func, single) {
activeEvents.push({
cls: obj.replace('NPMap.', ''),
event: event,
func: func,
id: id,
single: single || false
});
id++;
return id - 1;
},
/**
* Gets all the events or, optionally, just the events that have been added to a module.
* @param {String} obj (Optional)
* @return {Array}
*/
get: function(obj) {
var events = [];
if (!obj) {
events = activeEvents;
} else {
var cls = obj.replace('NPMap.', '');
for (var i = 0; i < activeEvents.length; i++) {
var active = activeEvents[i];
if (active.cls === cls) {
events.push(active);
}
}
}
return events;
},
/**
* Removes an event.
* @param {Number} id
* @return null
*/
remove: function(id) {
var cls,
index = -1;
for (var i = 0; i < activeEvents.length; i++) {
var activeEvent = activeEvents[i];
if (activeEvent.id === id) {
cls = activeEvent.cls;
index = i;
break;
}
}
if (index !== -1) {
activeEvents.splice(index, 1);
}
index = -1;
},
/**
* Triggers an event.
* @param {String} obj The name of the nested class, in "NPMap.ObjectName" format, to trigger the event for.
* @param {String} event The name of the event to trigger.
* @param {Object} e (Optional) The event object to pass to the event handler function.
* @return null
*/
trigger: function(obj, event, e) {
var cls = obj.replace('NPMap.', ''),
remove = [];
if (typeof NPMap[cls] !== 'undefined') {
for (var i = 0; i < activeEvents.length; i++) {
var v = activeEvents[i];
if (cls === v.cls && v.event === event) {
if (!e) {
v.func();
} else {
v.func(e);
}
if (v.single === true) {
remove.push(i);
}
}
}
_.each(remove, function(index) {
activeEvents.splice(index, 1);
});
} else {
var me = this;
console.log('Event ("' + obj + ', ' + event + '") triggered, but class does not exist. Looping in 100ms...');
setTimeout(function() {
me.trigger(obj, event, e);
}, 100);
}
}
};
});