-
Notifications
You must be signed in to change notification settings - Fork 2
/
ViewModel.js
101 lines (83 loc) · 1.83 KB
/
ViewModel.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
var Observable = require("FuseJS/Observable");
function ViewModel(module, desc) {
var model = {}
var validateCallback = undefined;
var self = {
invalidate: function() {
if (validateCallback) { return; }
if (!("computed" in desc)) { return; }
validateCallback = setTimeout(self.validate, 0);
},
validate: function() {
if (validateCallback)
{
clearTimeout(validateCallback);
for (var c in desc.computed[c]) {
model[c].value = desc.computed[c].call(self);
}
validateCallback = undefined;
}
}
}
if ("states" in desc) {
for (var s in desc.states) {
var val = desc.states[s];
if (val instanceof Observable) {
model[s] = val;
self[s] = val;
}
else {
model[s] = Obserable(val);
Object.defineProperty(self, s, {
get: function() {
self.invalidate();
return model[s].value;
},
set: function(value) {
model[s].value = value;
self.invalidate();
}
});
}
}
}
if ("computed" in desc) {
for (var c in desc.computed) {
var value = desc.computed[c].call(self);
model[c] = Observable(value);
Object.defineProperty(self, c, {
get: function() {
self.validate();
return model[c].value;
}
})
}
}
if ("methods" in desc) {
for (var m in desc.methods) {
var func = function() {
desc.methods[m].call(self);
self.invalidate();
}
model[m] = func;
self[m] = func;
}
}
if ("onchanged" in desc) {
// assuming module.root == "this", in regular <JavaScript> tags
// expected to be added to Fuse soon
var root = module.root;
for (var e in desc.onchanged) {
if (e in root) {
root[e].onValueChanged(module, function(value) {
desc.onchanged.call(self);
})
}
}
}
if ("created" in desc) {
desc.created.call(self);
}
return model;
}
module.exports = ViewModel;