Skip to content

Commit b3bcc5b

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

1 file changed

Lines changed: 72 additions & 2 deletions

File tree

emitter.js

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

24+
if (eventName.indexOf('.') !== -1) {
25+
var parentName = eventName.split('.')[0];
26+
var parentEventItems = collection[parentName];
27+
28+
parentEventItems.forEach(function (item) {
29+
if (item.student === student) {
30+
eventItem.callbackParent = item.callback;
31+
}
32+
});
33+
}
34+
collection[eventName].push(eventItem);
535
},
636

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

52+
events.forEach(function (event) {
53+
collection[event].forEach(function (item, i) {
54+
if (item.student === student) {
55+
collection[event].splice(i, 1);
56+
}
57+
});
58+
});
959
},
1060

61+
/**
62+
* Вызывает колбеки, которые в collection соотвествуют полученному имени события
63+
* @param eventName {String}
64+
*/
1165
emit: function (eventName) {
66+
countEmit++;
67+
68+
if (countSeveral && countEmit > countSeveral) {
69+
return;
70+
}
1271

72+
if (countThrough && countEmit % countThrough !== 0) {
73+
return;
74+
}
75+
76+
var eventItems = collection[eventName];
77+
eventItems && eventItems.forEach(function (item) {
78+
item.callback();
79+
item.callbackParent && item.callbackParent();
80+
});
1381
},
1482

1583
several: function (eventName, student, callback, n) {
16-
84+
this.on(eventName, student, callback);
85+
countSeveral = isNaN(n) ? 0 : n;
1786
},
1887

1988
through: function (eventName, student, callback, n) {
20-
89+
this.on(eventName, student, callback);
90+
countThrough = n;
2191
}
2292
};
2393
};

0 commit comments

Comments
 (0)