-
Notifications
You must be signed in to change notification settings - Fork 330
/
createStore.js
61 lines (55 loc) · 1.81 KB
/
createStore.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
var _ = require('./utils');
/**
* Creates an event emitting Data Store
*
* @param {Object} definition The data store object definition
*/
module.exports = function(definition) {
var store = new _.EventEmitter(),
eventLabel = "change";
function Store() {
this.registered = [];
if (this.init && _.isFunction(this.init)) {
this.init();
}
}
_.extend(Store.prototype, definition);
Store.prototype.listenTo = function(listenable, callback) {
if (listenable === this) {
throw Error("Store is not able to listen to itself");
}
if (!_.isFunction(listenable.listen)) {
throw new TypeError(listenable + " is missing a listen method");
}
if (this.hasListener(listenable)) {
throw Error("Store cannot listen to this listenable because of circular loop");
}
this.registered.push(listenable);
return listenable.listen(callback, this);
};
Store.prototype.listen = function(callback, bindContext) {
var eventHandler = function(args) {
callback.apply(bindContext, args);
};
eventHandler.l = callback;
store.addListener(eventLabel, eventHandler);
return function() {
store.removeListener(eventLabel, eventHandler);
};
};
Store.prototype.trigger = function() {
store.emit(eventLabel, arguments);
};
Store.prototype.hasListener = function(listenable) {
var i = 0,
listener;
for (;i < this.registered.length; ++i) {
listener = this.registered[i];
if (listener === listenable || listener.hasListener && listener.hasListener(listenable)) {
return true;
}
}
return false;
};
return new Store();
};