Created
June 19, 2015 14:11
-
-
Save volodymyrlut/ee0a35f26953cdf4f382 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var a = {}; | |
function emitter(obj) { | |
obj.emit = function(en, data){ | |
if(this[en]){ | |
for (var i = 0; i < this[en].length; i++){ | |
this[en][i][0].apply(this, [data]); | |
if (this[en][i][1]){ | |
this[en].splice(i, 1); | |
i--; | |
} | |
} | |
} | |
}; | |
obj.one = function(en, cb){ | |
this[en] = this[en] || []; | |
this[en].push([cb, true]); | |
}; | |
obj.off = function(en){ | |
delete this[en]; | |
}; | |
obj.on = function(en, cb){ | |
this[en] = this[en] || []; | |
this[en].push([cb, false]); | |
}; | |
return obj; | |
} | |
a = emitter(a); | |
a.emit('eventName', 2); | |
//відбувається івент 'eventName', передаються дані {1: 2} | |
a.emit('eventName', 2); | |
//еміт події | |
a.off('eventName'); | |
//всі event listeners вимикаються | |
a.one('eventName', function (data) { | |
console.log("called once" + data); | |
}); | |
//event listener який виконується лише раз. | |
a.on('eventName', function (data) { | |
console.log("called mutiple times" + data); | |
}); | |
//типовий event listener | |
a.emit('eventName', 1); | |
a.emit('eventName', 2); | |
a.off('eventName'); | |
//вимикаються усі listener`и | |
a.emit('eventName', 3); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment