/
o_O.list.js
120 lines (95 loc) · 2.02 KB
/
o_O.list.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/* ___ _ _ _
___ / _ \ | (_)___| |_
/ _ \ | | | || | / __| __|
| (_) | | |_| || | \__ \ |_
\___/___\___(_)_|_|___/\__|
|_____| */
!function() {
function list(models) {
if(this.constructor != list) return new list(models)
this.objects = {}
this.count = o_O(0)
o_O.eventize(this)
if(models) {
for(var i=0; i< models.length;i++) {
this.add(models[i])
}
}
}
var proto = list.prototype
proto.genId = function() {
return ++this.genId.id
}
proto.genId.id = 0
proto.add = function(o) {
o.id = o.id || this.genId()
this.objects[o.id] = o
o.list = this
if(o.on) {
o.on('*', this._onevent, this)
o.emit('add', o, this)
}
else
this.emit('add', o)
this.count.incr()
}
proto._onevent = function(ev, o, list) {
if ((ev == 'add' || ev == 'remove') && list != this) return
if (ev == 'destroy') {
this.remove(o)
}
this.emit.apply(this, arguments)
}
proto.filter = function(fn) {
var ret = [];
this.each(function(o) {
if(fn(o)) ret.push(o)
})
return ret
}
proto.find = function(i) {
return this.objects[i]
}
proto.each = proto.forEach = function(fn) {
this.count(); // force the dependency
for(var i in this.objects)
fn.call(this, this.find(i), i)
}
proto.remove = function(o) {
if(undefined === this.objects[o.id])
return
delete this.objects[o.id]
this.count.incr(-1)
if(this == o.list) delete o.list
if(o.off) {
o.emit('remove', o, this)
o.off('all', this._onevent, this)
}else{
this.emit('remove', o)
}
}
proto.renderOne = function(item, $el) {
$(getTemplate($el)).each(function(i, elem) {
var $$ = $(elem)
$$.appendTo($el)
o_O.bind(item, $$)
})
}
proto.bind = function($el) {
var self = this
this.on('add', function(item) {
self.renderOne(item, $el)
})
this.on('remove', this.removeElement, this)
}
proto.removeElement = function(item) {
$(item.el).remove()
}
proto.toString = function() {
return '#<list>'
}
proto.extend = function() {
return inherits(this)
}
o_O.list = list
}()