UNPKG

1.45 kBJavaScriptView Raw
1
2/* litejs.com/MIT-LICENSE.txt */
3
4
5
6El.bindings.list = function(node, list, extra, val) {
7 var child = node._child
8 , data = this
9 , extraLen = 0
10
11 if (!child) {
12 child = node._child = node.removeChild(node.firstChild)
13 }
14
15 if (!list || node._list == list) return
16
17 if (node._list) clear()
18
19 node._list = data.list = list
20
21 El.on(node, "kill", clear)
22
23 El.addClass(node, "loading")
24
25 if (extra) {
26 extra.each(clone)
27 extraLen = extra.length
28 }
29
30 list
31 .each(clone)
32 .on("add", clone).on("remove", remove)
33 .then(function() {
34 if (val !== void 0 && El.val(node) !== val) {
35 if (!this.get(val)) {
36 clone({id:val,name:val}, extraLen)
37 extraLen++
38 }
39 El.val(node, val)
40 }
41 El.rmClass(node, "loading")
42 })
43
44 // Do not render childs when list initialized
45 return true
46
47 function clone(item, pos) {
48 var clone = child.cloneNode(true)
49 , scope = El.scope(clone, data)
50 scope.item = item.data || item || {id:item,name:item}
51 scope.model = item
52 scope.pos = pos
53 function up() {
54 El.render(clone, scope)
55 }
56 if (item.on) {
57 item.on("change", up)
58 El.on(clone, "kill", function(){
59 item.off("change", up)
60 })
61 }
62 El.append(node, clone, extraLen + pos)
63 return El.render(clone, scope)
64 }
65
66 function remove(item, pos) {
67 El.kill(node.childNodes[extraLen + pos])
68 }
69
70 function clear() {
71 var list = node._list
72 El.empty(node)
73 if (list) {
74 node._list = null
75 list.off("add", clone).off("remove", remove)
76 }
77 }
78}
79