forked from nullstack/nullstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbindable.js
More file actions
59 lines (54 loc) · 1.97 KB
/
bindable.js
File metadata and controls
59 lines (54 loc) · 1.97 KB
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
export default class Bindable {
match({node}) {
return (
node !== undefined &&
node.attributes !== undefined &&
node.attributes.bind !== undefined &&
node.attributes.source !== undefined
)
}
transform({node, scope}) {
const target = node.attributes.source;
if(node.type === 'textarea') {
node.children = [target[node.attributes.bind]];
} else if(node.type === 'input' && node.attributes.type === 'checkbox') {
node.attributes.checked = target[node.attributes.bind];
} else {
node.attributes.value = target[node.attributes.bind];
}
node.attributes.name = node.attributes.name || node.attributes.bind;
if(scope.context.environment.client) {
this._attatchEvent(node);
}
}
_attatchEvent(node) {
const target = node.attributes.source;
let eventName = 'oninput';
let valueName = 'value';
if(node.attributes.type === 'checkbox' || node.attributes.type === 'radio') {
eventName = 'onclick';
valueName = 'checked';
} else if(node.type !== 'input' && node.type !== 'textarea') {
eventName = 'onchange';
}
const originalEvent = node.attributes[eventName];
node.attributes[eventName] = (scope) => {
const {event, value} = scope;
if(valueName == 'checked') {
target[node.attributes.bind] = event.target[valueName];
} else if(target[node.attributes.bind] === true || target[node.attributes.bind] === false) {
target[node.attributes.bind] = event ? (event.target[valueName] == 'true') : value;
} else if(typeof target[node.attributes.bind] === 'number') {
target[node.attributes.bind] = parseFloat(event ? event.target[valueName] : value) || 0;
} else {
target[node.attributes.bind] = event ? event.target[valueName] : value;
}
//client.update();
if(originalEvent !== undefined) {
setTimeout(() => {
originalEvent({...node.attributes, ...scope});
}, 0);
}
}
}
}