-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinding-accessor.js
54 lines (44 loc) · 1.26 KB
/
binding-accessor.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
var acorn = require('acorn')
var applyTransforms = require('./ast-transforms')
module.exports = BindingAccessor
module.exports.parseBinding = parseBinding
function BindingAccessor (el) {
this.el = el
}
BindingAccessor.prototype.get = function () {
var bindings = this.el.getAttribute('data-bind-parsed');
if (bindings) {
return JSON.parse(bindings);
}
var str = this.el.getAttribute('data-bind')
if (!str) return false
var parsedBinding = parseBinding(str)
parsedBinding.forEach(function (b) {
b.value = applyTransforms(b.value)
})
this.set(parsedBinding)
return parsedBinding;
}
BindingAccessor.prototype.set = function (val) {
if (typeof val == 'object') {
val = JSON.stringify(val)
this.el.setAttribute('data-bind-parsed', val)
return
}
return this.el.setAttribute('data-bind', val)
}
function parseBinding (str) {
if (!str) return [];
var bindingExpression = '({' + str + '})'
var ast = acorn.parse(bindingExpression)
var bindingNodes = ast.body[0].expression.properties
return bindingNodes.map(function (b) {
b.key = b.key.name || b.key.value;
b.raw = bindingExpression.substring(b.value.start, b.value.end)
return b;
})
}
module.exports.test = function () {
var e = "text: name + 3, click: doStuff"
console.log(parseBinding(e))
}