This repository has been archived by the owner on Oct 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 152
/
callbacks.js
64 lines (58 loc) · 2.19 KB
/
callbacks.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
// CallbackManager
// ---------------
// A general-purpose event binding manager used by `Map`
// and `RequestManager`
// Construct a new CallbackManager, with an list of
// supported events.
MM.CallbackManager = function(owner, events) {
this.owner = owner;
this.callbacks = {};
for (var i = 0; i < events.length; i++) {
this.callbacks[events[i]] = [];
}
};
// CallbackManager does simple event management for modestmaps
MM.CallbackManager.prototype = {
// The element on which callbacks will be triggered.
owner: null,
// An object of callbacks in the form
//
// { event: function }
callbacks: null,
// Add a callback to this object - where the `event` is a string of
// the event name and `callback` is a function.
addCallback: function(event, callback) {
if (typeof(callback) == 'function' && this.callbacks[event]) {
this.callbacks[event].push(callback);
}
},
// Remove a callback. The given function needs to be equal (`===`) to
// the callback added in `addCallback`, so named functions should be
// used as callbacks.
removeCallback: function(event, callback) {
if (typeof(callback) == 'function' && this.callbacks[event]) {
var cbs = this.callbacks[event],
len = cbs.length;
for (var i = 0; i < len; i++) {
if (cbs[i] === callback) {
cbs.splice(i,1);
break;
}
}
}
},
// Trigger a callback, passing it an object or string from the second
// argument.
dispatchCallback: function(event, message) {
if(this.callbacks[event]) {
for (var i = 0; i < this.callbacks[event].length; i += 1) {
try {
this.callbacks[event][i](this.owner, message);
} catch(e) {
//console.log(e);
// meh
}
}
}
}
};