|
1 | 1 | module.exports = function () { |
| 2 | + var collection = {}; |
| 3 | + var countSeveral = 0; |
| 4 | + var countEmit = 0; |
| 5 | + var countThrough; |
| 6 | + |
2 | 7 | return { |
| 8 | + /** |
| 9 | + * Наполняет collection данными про вызванное событие и соотвествующие ему данные |
| 10 | + * @param eventName {String} |
| 11 | + * @param student {Object} |
| 12 | + * @param callback {Function} |
| 13 | + */ |
3 | 14 | 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 | + }; |
4 | 23 |
|
| 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); |
5 | 35 | }, |
6 | 36 |
|
| 37 | + /** |
| 38 | + * Удаляет оъект из collection |
| 39 | + * @param eventName {String} |
| 40 | + * @param student {Object} |
| 41 | + */ |
7 | 42 | 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 | + } |
8 | 51 |
|
| 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 | + }); |
9 | 59 | }, |
10 | 60 |
|
| 61 | + /** |
| 62 | + * Вызывает колбеки, которые в collection соотвествуют полученному имени события |
| 63 | + * @param eventName {String} |
| 64 | + */ |
11 | 65 | emit: function (eventName) { |
| 66 | + countEmit++; |
| 67 | + |
| 68 | + if (countSeveral && countEmit > countSeveral) { |
| 69 | + return; |
| 70 | + } |
12 | 71 |
|
| 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 | + }); |
13 | 81 | }, |
14 | 82 |
|
15 | 83 | several: function (eventName, student, callback, n) { |
16 | | - |
| 84 | + this.on(eventName, student, callback); |
| 85 | + countSeveral = isNaN(n) ? 0 : n; |
17 | 86 | }, |
18 | 87 |
|
19 | 88 | through: function (eventName, student, callback, n) { |
20 | | - |
| 89 | + this.on(eventName, student, callback); |
| 90 | + countThrough = n; |
21 | 91 | } |
22 | 92 | }; |
23 | 93 | }; |
0 commit comments