-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCollections.js
More file actions
80 lines (80 loc) · 2.69 KB
/
Collections.js
File metadata and controls
80 lines (80 loc) · 2.69 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
(function(global) {
'use strict';
global.Collection = function(items) {
this.length = 0;
this._data = [];
this.listeners = {
'get': [],
'set': [],
'change': [],
'remove': []
};
if (this.isArray(items)) {
this._data = items;
this.length = this._data.length;
} else {
for (var i = items - 1; i >= 0; i--) {
this._data.push(0);
};
}
};
global.Collection.prototype.isArray = function(data) {
return data.constructor.toString().indexOf("Array") > -1;
};
global.Collection.prototype.fireEvent = function(event, data) {
if (!this.listeners[event]) {
return;
}
var ls = this.listeners[event];
for (var i = ls.length - 1; i >= 0; i--) {
ls[i].apply(this, data);
};
};
global.Collection.prototype.getItem = function(index) {
this.fireEvent('get', [index]);
return this._data[index];
};
global.Collection.prototype.setItem = function(index, data) {
if (this._data[index] === 'undefined') {
this.fireEvent('set', [index, data]);
} else {
this.fireEvent('change', [index, data]);
}
this.length = this._data.length;
return this._data[index];
};
global.Collection.prototype.push = function(data) {
var i = this._data.push(data);
this.fireEvent('set', [i, data]);
this.length = this._data.length;
return i;
};
global.Collection.prototype.pop = function() {
var item = this._data.pop(data);
this.length = this._data.length;
this.fireEvent('remove', [this.length, data]);
return item;
};
global.Collection.prototype.removeItem = function(index) {
this.fireEvent('remove', [index]);
return this._data[index].splice(index, 1);
};
global.Collection.prototype.forEach = function(cb) {
for (var i = this._data.length - 1; i >= 0; i--) {
cb && cb.apply && cb.apply(this, [this._data[i]]);
};
};
global.Collection.prototype.addEventListener = function(event, handler, context) {
if (!this.listeners[event]) {
throw new Error('there is no event ' + event);
}
context = context || this;
var ihandler = function() {
handler.apply(context, arguments);
}
return this.listeners[event].push(ihandler);
};
global.Collection.prototype.removeEventListener = function(event, index) {
this.listeners[event] && this.listeners[event][index] && this.listeners[event].splice(index, 1);
};
})(this)