forked from rse/componentjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomponent-3-patt-6-observable.js
82 lines (73 loc) · 2.98 KB
/
component-3-patt-6-observable.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
/*
** ComponentJS -- Component System for JavaScript <http://componentjs.com>
** Copyright (c) 2009-2013 Ralf S. Engelschall <http://engelschall.com>
**
** This Source Code Form is subject to the terms of the Mozilla Public
** License, v. 2.0. If a copy of the MPL was not distributed with this
** file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/* generic pattern: observable */
$cs.pattern.observable = $cs.trait({
dynamics: {
/* internal state */
__listener: {}
},
protos: {
/* attach a listener */
listen: function () {
/* determine parameters */
var params = $cs.params("listen", arguments, {
name: { pos: 0, req: true },
ctx: { def: this },
func: { pos: 1, req: true },
args: { pos: "...", def: [] },
spec: { def: null } /* customized matching */
});
/* attach listener information */
var id = _cs.cid();
this.__listener[id] = params;
return id;
},
/* check for an attached listener */
listening: function () {
/* determine parameters */
var params = $cs.params("listening", arguments, {
id: { pos: 0, req: true }
});
/* check whether listener is attached */
return (typeof this.__listener[params.id] !== "undefined");
},
/* detach a listener */
unlisten: function () {
/* determine parameters */
var params = $cs.params("unlisten", arguments, {
id: { pos: 0, req: true }
});
/* detach parameters from component */
if (typeof this.__listener[params.id] === "undefined")
throw _cs.exception("unlisten", "listener not found");
var listener = this.__listener[params.id];
delete this.__listener[params.id];
return listener;
},
/* notify all listeners */
notify: function () {
/* determine parameters */
var params = $cs.params("notify", arguments, {
name: { pos: 0, req: true },
args: { pos: "...", def: [] },
matches: { def: function (p, l) { return p.name === l.name; } } /* customized matching */
});
/* notify all listeners */
for (var id in this.__listener) {
if (_cs.isown(this.__listener, id)) {
var listener = this.__listener[id];
if (params.matches(params, listener)) {
var args = _cs.concat(listener.args, params.args);
listener.func.apply(listener.ctx, args);
}
}
}
}
}
});