custom-listenable
Version:
Create custom listenable with addListener and removeListener methods.
39 lines (36 loc) • 1.13 kB
JavaScript
;
var listenable = function () {
var listeners = [];
var findIndex = function (callback) {
return listeners.findIndex(function (listener) { return listener.callback === callback; });
};
var addListener = function (callback, options) {
if (options === void 0) { options = {}; }
// Prevent duplicate listeners
if (findIndex(callback) >= 0) {
return;
}
listeners.push({ callback: callback, options: options });
};
var removeListener = function (callback) {
var listenerIndex = findIndex(callback);
if (listenerIndex >= 0) {
listeners.splice(listenerIndex, 1);
}
};
var emit = function (data) {
listeners.forEach(function (listener) {
listener.callback(data);
if (listener.options.once) {
removeListener(listener.callback);
}
});
};
return {
addListener: addListener,
removeListener: removeListener,
emit: emit,
};
};
exports.listenable = listenable;
//# sourceMappingURL=index.js.map