forked from urfu-2016/javascript-task-5
-
Notifications
You must be signed in to change notification settings - Fork 0
/
emitter.js
85 lines (71 loc) · 2.38 KB
/
emitter.js
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
'use strict';
getEmitter.isStar = true;
module.exports = getEmitter;
function getEmitter() {
var events = {};
function getEventsForEmit(event) {
var nameOfEvent = '';
return event
.split('.')
.map(function (e) {
nameOfEvent += e + '.';
return nameOfEvent.slice(0, -1);
})
.reverse();
}
return {
on: function (event, context, handler) {
if (!events.hasOwnProperty(event)) {
events[event] = [];
}
events[event].push({
context: context,
handler: handler,
iteration: 0
});
return this;
},
off: function (event, context) {
Object.keys(events).forEach(function (eventForOff) {
if (eventForOff === event || eventForOff.indexOf(event + '.') === 0) {
events[eventForOff] = events[eventForOff].filter(function (record) {
return record.context !== context;
});
}
});
return this;
},
emit: function (event) {
var eventsForEmit = getEventsForEmit(event);
eventsForEmit.forEach(function (eventForEmit) {
if (events.hasOwnProperty(eventForEmit)) {
events[eventForEmit].forEach(function (record) {
record.handler.call(record.context, record);
});
}
});
return this;
},
several: function (event, context, handler, times) {
var handlerWrapper = function (record) {
record.iteration++;
if (record.iteration <= times) {
handler.call(record.context);
}
};
this.on(event, context, handlerWrapper);
return this;
},
through: function (event, context, handler, frequency) {
var handlerWrapper = function (record) {
if (record.iteration % frequency === 0) {
handler.call(record.context);
record.iteration = 0;
}
record.iteration++;
};
this.on(event, context, handlerWrapper);
return this;
}
};
}