|
1 | 1 | module.exports = function () { |
| 2 | + var collection = {}; |
| 3 | + |
2 | 4 | return { |
| 5 | + /** |
| 6 | + * Наполняет collection данными про вызванное событие и соотвествующие ему данные |
| 7 | + * @param eventName {String} |
| 8 | + * @param student {Object} |
| 9 | + * @param callback {Function} |
| 10 | + */ |
3 | 11 | 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]; |
4 | 24 |
|
| 25 | + parentEventItems.forEach(function (item) { |
| 26 | + if (item.student === student) { |
| 27 | + eventItem.callbackParent = item.callback; |
| 28 | + } |
| 29 | + }); |
| 30 | + } |
| 31 | + collection[eventName].push(eventItem); |
5 | 32 | }, |
6 | 33 |
|
| 34 | + /** |
| 35 | + * Удаляет оъект из collection |
| 36 | + * @param eventName {String} |
| 37 | + * @param student {Object} |
| 38 | + */ |
7 | 39 | 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 | + } |
8 | 48 |
|
| 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 | + }); |
9 | 56 | }, |
10 | 57 |
|
| 58 | + /** |
| 59 | + * Вызывает колбеки, которые в collection соотвествуют полученному имени события |
| 60 | + * @param eventName {String} |
| 61 | + */ |
11 | 62 | emit: function (eventName) { |
| 63 | + var eventItems = collection[eventName]; |
12 | 64 |
|
| 65 | + eventItems && eventItems.forEach(function (item) { |
| 66 | + item.callback(); |
| 67 | + item.callbackParent && item.callbackParent(); |
| 68 | + }); |
13 | 69 | }, |
14 | 70 |
|
| 71 | + //TODO: реализую |
15 | 72 | several: function (eventName, student, callback, n) { |
16 | 73 |
|
17 | 74 | }, |
18 | 75 |
|
| 76 | + //TODO: реализую |
19 | 77 | through: function (eventName, student, callback, n) { |
20 | 78 |
|
21 | 79 | } |
|
0 commit comments