forked from rse/componentjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomponent-3-patt-8-cmd.js
81 lines (73 loc) · 2.46 KB
/
component-3-patt-8-cmd.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
/*
** 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: command */
$cs.pattern.command = $cs.clazz({
mixin: [
$cs.pattern.observable
],
dynamics: {
/* standard attributes */
ctx: $cs.attribute("ctx", null),
func: $cs.attribute("func", $cs.nop),
args: $cs.attribute("args", []),
async: $cs.attribute("async", false),
/* usually observed attribute */
enabled: $cs.attribute({
name: "enabled",
def: true,
validate: function (v) { return typeof v === "boolean"; }
})
},
protos: {
/* method: execute the command */
execute: function (caller_args, caller_result) {
if (!this.enabled())
return;
var args = [];
if (this.async()) {
args.push(function (value) {
if (typeof caller_result === "function")
caller_result(value);
});
}
args = _cs.concat(args, this.args(), caller_args);
return this.func().apply(this.ctx(), args);
}
}
});
/* command factory */
$cs.command = function () {
/* determine parameters */
var params = $cs.params("command", arguments, {
ctx: { def: null },
func: { pos: 0, req: true },
args: { pos: "...", def: [] },
async: { def: false },
enabled: { def: true },
wrap: { def: false }
});
/* create new command */
var cmd = new $cs.pattern.command();
/* configure command */
cmd.ctx (params.ctx);
cmd.func (params.func);
cmd.args (params.args);
cmd.async (params.async);
cmd.enabled(params.enabled);
/* optionally wrap into convenient "execute" closure */
var result = cmd;
if (params.wrap) {
result = function () {
var args = _cs.concat(arguments);
return arguments.callee.command.execute.call(arguments.callee.command, args);
};
result.command = cmd;
}
return result;
};