Skip to content

Commit d532d0f

Browse files
author
Natalia Makishvili
committed
Natalia Makishvili
1 parent aaaa19f commit d532d0f

1 file changed

Lines changed: 58 additions & 0 deletions

File tree

emitter.js

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,79 @@
11
module.exports = function () {
2+
var collection = {};
3+
24
return {
5+
/**
6+
* Наполняет collection данными про вызванное событие и соотвествующие ему данные
7+
* @param eventName {String}
8+
* @param student {Object}
9+
* @param callback {Function}
10+
*/
311
on: function (eventName, student, callback) {
12+
if (!collection[eventName]) {
13+
collection[eventName] = [];
14+
}
15+
16+
var eventItem = {
17+
student: student,
18+
callback: callback.bind(student)
19+
};
20+
21+
if (eventName.indexOf('.') !== -1) {
22+
var parentName = eventName.split('.')[0];
23+
var parentEventItems = collection[parentName];
424

25+
parentEventItems.forEach(function (item) {
26+
if (item.student === student) {
27+
eventItem.callbackParent = item.callback;
28+
}
29+
});
30+
}
31+
collection[eventName].push(eventItem);
532
},
633

34+
/**
35+
* Удаляет оъект из collection
36+
* @param eventName {String}
37+
* @param student {Object}
38+
*/
739
off: function (eventName, student) {
40+
var events;
41+
if (eventName.indexOf('.') === -1) {
42+
events = Object.keys(collection).filter(function (name) {
43+
return name.indexOf(eventName) !== -1;
44+
});
45+
} else {
46+
events = [eventName];
47+
}
848

49+
events.forEach(function (event) {
50+
collection[event].forEach(function (item, i) {
51+
if (item.student === student) {
52+
collection[event].splice(i, 1);
53+
}
54+
});
55+
});
956
},
1057

58+
/**
59+
* Вызывает колбеки, которые в collection соотвествуют полученному имени события
60+
* @param eventName {String}
61+
*/
1162
emit: function (eventName) {
63+
var eventItems = collection[eventName];
1264

65+
eventItems && eventItems.forEach(function (item) {
66+
item.callback();
67+
item.callbackParent && item.callbackParent();
68+
});
1369
},
1470

71+
//TODO: реализую
1572
several: function (eventName, student, callback, n) {
1673

1774
},
1875

76+
//TODO: реализую
1977
through: function (eventName, student, callback, n) {
2078

2179
}

0 commit comments

Comments
 (0)