forked from urfu-2016/javascript-task-5
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathemitter.js
More file actions
101 lines (89 loc) · 3.19 KB
/
emitter.js
File metadata and controls
101 lines (89 loc) · 3.19 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
94
95
96
97
98
99
100
101
'use strict';
/**
* Сделано задание на звездочку
* Реализованы методы several и through
*/
getEmitter.isStar = false;
module.exports = getEmitter;
/**
* Возвращает новый emitter
* @returns {Object}
*/
function getEmitter() {
return {
subscriptions: {},
/**
* Подписаться на событие
* @param {String} event
* @param {Object} context
* @param {Function} handler
*/
on: function (event, context, handler) {
if (!this.subscriptions.hasOwnProperty(event)) {
this.subscriptions[event] = [];
}
this.subscriptions[event].push({
context: context,
handler: handler
});
return this;
},
/**
* Отписаться от события
* @param {String} event
* @param {Object} context
* @returns {Object}
*/
off: function (event, context) {
var eventWithDot = event + '.';
var subscriptionsForOff = Object.keys(this.subscriptions).filter(function (value) {
return value === event || value.indexOf(eventWithDot) === 0;
});
subscriptionsForOff.forEach(function (eventForOff) {
this.subscriptions[eventForOff] = this.subscriptions[eventForOff].filter(function
(value) {
return value.context !== context;
});
}, this);
return this;
},
/**
* Уведомить о событии
* @param {String} event
* @returns {Object}
*/
emit: function (event) {
while (event) {
if (this.subscriptions.hasOwnProperty(event)) {
this.subscriptions[event].forEach(function (contextAndHandler) {
contextAndHandler.handler.call(contextAndHandler.context);
});
}
event = event.substring(0, event.lastIndexOf('.'));
}
return this;
},
/**
* Подписаться на событие с ограничением по количеству полученных уведомлений
* @star
* @param {String} event
* @param {Object} context
* @param {Function} handler
* @param {Number} times – сколько раз получить уведомление
*/
several: function (event, context, handler, times) {
console.info(event, context, handler, times);
},
/**
* Подписаться на событие с ограничением по частоте получения уведомлений
* @star
* @param {String} event
* @param {Object} context
* @param {Function} handler
* @param {Number} frequency – как часто уведомлять
*/
through: function (event, context, handler, frequency) {
console.info(event, context, handler, frequency);
}
};
}