-
Notifications
You must be signed in to change notification settings - Fork 0
/
eventhandler.js
44 lines (36 loc) · 1.19 KB
/
eventhandler.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
/*
eventhandler.js
Simple event handler. Supports attaching events to callbacks and triggering
events.
TODO:
Add a method for removing events.
*/
define(function() {
var EventHandler = function(handlers) {
this.handlers = {};
for (event in handlers)
this.on(event, handlers[event]);
};
EventHandler.prototype.on = function(events, handler, context) {
if (typeof events === 'string')
events = events.split(' ');
if (context) {
var _handler = handler; // To avoid infinite recursion.
handler = function() {_handler.apply(context, arguments)};
}
for (var i=0; i < events.length; i++) {
var event = events[i];
if (event in this.handlers)
this.handlers[event].push(handler);
else
this.handlers[event] = [handler];
}
};
EventHandler.prototype.emit = function(event, args) {
var handlers = this.handlers[event];
if (handlers)
for (var i=0; i < handlers.length; i++)
handlers[i].apply(null, Array.prototype.slice.call(arguments, 1));
};
return EventHandler;
});