Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 47 additions & 4 deletions emitter.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,41 +4,84 @@
* Сделано задание на звездочку
* Реализованы методы several и through
*/
getEmitter.isStar = true;
getEmitter.isStar = false;
module.exports = getEmitter;

/**
* Возвращает новый emitter
* @returns {Object}
*/
function getEmitter() {

return {

getChildrenEvents: function (event) {
var events = event.split('.');
for (var i = 1; i < events.length; i++) {
events[i] = events[i - 1].concat('.').concat(events[i]);
}

return events.reverse();
},

subscriptions: {},

/**
* Подписаться на событие
* @param {String} event
* @param {Object} context
* @param {Function} handler
* @returns {Object}
*/
on: function (event, context, handler) {
console.info(event, context, handler);

if (!this.subscriptions.hasOwnProperty(event)) {
this.subscriptions[event] = [];
}

this.subscriptions[event].push({
context: context,
handler: handler.bind(context)
});

return this;
},

/**
* Отписаться от события
* @param {String} event
* @param {Object} context
* @returns {Object}
*/
off: function (event, context) {
console.info(event, context);
for (var subscription in this.subscriptions) {
if (this.subscriptions.hasOwnProperty(subscription) && (subscription === event ||
subscription.indexOf(event.concat('.') === 0))) {
this.subscriptions[event] = this.subscriptions[event].filter(function (name) {
return name.context !== context;
});
}
}

return this;
},

/**
* Уведомить о событии
* @param {String} event
* @returns {Object}
*/
emit: function (event) {
console.info(event);
var subscriptions = this.subscriptions;
(this.getChildrenEvents(event)).forEach(function (subscription) {
if (subscriptions.hasOwnProperty(subscription)) {
subscriptions[subscription].forEach(function (element) {
element.handler();
});
}
});

return this;
},

/**
Expand Down