forked from urfu-2015/javascript-tasks-5
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathemitter.js
More file actions
93 lines (81 loc) · 2.93 KB
/
emitter.js
File metadata and controls
93 lines (81 loc) · 2.93 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
81
82
83
84
85
86
87
88
89
90
91
92
93
module.exports = function () {
var collection = {};
var countSeveral = 0;
var countEmit = 0;
var countThrough;
return {
/**
* Наполняет collection данными про вызванное событие и соотвествующие ему данные
* @param eventName {String}
* @param student {Object}
* @param callback {Function}
*/
on: function (eventName, student, callback) {
if (!collection[eventName]) {
collection[eventName] = [];
}
var eventItem = {
student: student,
callback: callback.bind(student)
};
if (eventName.indexOf('.') !== -1) {
var parentName = eventName.split('.')[0];
var parentEventItems = collection[parentName];
parentEventItems.forEach(function (item) {
if (item.student === student) {
eventItem.callbackParent = item.callback;
}
});
}
collection[eventName].push(eventItem);
},
/**
* Удаляет оъект из collection
* @param eventName {String}
* @param student {Object}
*/
off: function (eventName, student) {
var events;
if (eventName.indexOf('.') === -1) {
events = Object.keys(collection).filter(function (name) {
return name.indexOf(eventName) !== -1;
});
} else {
events = [eventName];
}
events.forEach(function (event) {
collection[event].forEach(function (item, i) {
if (item.student === student) {
collection[event].splice(i, 1);
}
});
});
},
/**
* Вызывает колбеки, которые в collection соотвествуют полученному имени события
* @param eventName {String}
*/
emit: function (eventName) {
countEmit++;
if (countSeveral && countEmit > countSeveral) {
return;
}
if (countThrough && countEmit % countThrough !== 0) {
return;
}
var eventItems = collection[eventName];
eventItems && eventItems.forEach(function (item) {
item.callback();
item.callbackParent && item.callbackParent();
});
},
several: function (eventName, student, callback, n) {
this.on(eventName, student, callback);
countSeveral = isNaN(n) ? 0 : n;
},
through: function (eventName, student, callback, n) {
this.on(eventName, student, callback);
countThrough = n;
}
};
};