This repository has been archived by the owner on Nov 25, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
76 lines (63 loc) · 1.89 KB
/
index.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
var utils = require('reactive/lib/utils')
module.exports = plugin
function plugin (instance) {
if (instance == null || typeof instance.bind !== 'function')
throw new Error('Requires Reactive instance')
instance.bind('data-remove', plugin.binding)
}
plugin.binding = function (el, expr) {
if (isFalse(expr)) return
var reactive = this.reactive
, binding = this
, isBool = expr=='true'
, hasInterpolation = !isBool && utils.hasInterpolation(expr)
update()
// subscribe to changes
if (hasInterpolation) {
utils.interpolationProps(expr).forEach(function(prop){
reactive.sub(prop, update)
})
} else if (!isBool) {
// expr is a property name
reactive.sub(expr, update)
}
function update(){
var place = binding.placeholder
, parent = el.parentNode
, remove = true
// hack for childview of an each-binding,
// where the Reactive instance is created
// before inserting into DOM (so it has
// no parentNode at this point).
if (!parent && !place) {
binding.loops = (binding.loops || 0) + 1
if (binding.loops<15) setTimeout(update, 100)
return
}
delete binding.loops
if (hasInterpolation) {
// todo: make it work with binding.interpolate()
var thruthy = utils.interpolate(expr, function(prop, fn){
if (fn) return fn(reactive)
else return reactive.get(prop)
})
remove = !isFalse(thruthy)
} else if (!isBool) {
// property name
remove = !isFalse(binding.value(expr))
}
if (place) {
if (remove) return
// reinsert
place.parentNode.replaceChild(el, place)
delete binding.placeholder
} else if (remove) {
// remove
binding.placeholder = document.createTextNode('')
parent.replaceChild(binding.placeholder, el)
}
}
}
function isFalse(val) {
return !val || val==='false' || val==='undefined'
}