diffusion
Version:
Diffusion JavaScript client
90 lines (76 loc) • 2.39 kB
JavaScript
/*eslint valid-jsdoc: "off"*/
var _implements = require('util/interface')._implements;
var Stream = require('../../events/stream');
/**
* Set one or more properties on an object;
*
* @param {Object} object - The object to attach properties to
* @param {String|Object} key - The key, or an object map of properties
* @param {*} value - If the key is a string, this is the value to be associated with it
*
* @returns The object, with attached properties
*/
function attach(object, key, value, allowedEvents) {
if (typeof key === 'object') {
for (var k in key) {
attach(object, k, key[k], allowedEvents);
}
} else if (value) {
if (object[key] === undefined) {
if (allowedEvents && allowedEvents.indexOf(key) === -1) {
throw new Error('Event ' + key + ' not emitted on this stream, allowed events are ' + allowedEvents);
}
object[key] = [];
}
object[key].push(value);
}
return object;
}
/**
* Remove one or more properties from an object
*
* @param {Object} object - The object to remove properties from
* @param {String|Object} key - The key, or an object map of properties
* @param {*} value - If the key is a string, this is the value to remove from it
*
* @returns The object, sans specified properties
*/
function remove(object, key, value) {
if (typeof key === 'object') {
for (var k in key) {
remove(object, k, key[k]);
}
} else if (object[key]) {
if (value) {
object[key] = object[key].filter(function(e) {
return e !== value;
});
} else {
object[key] = [];
}
}
return object;
}
function StreamImpl(listeners, error, close, events) {
var allowedEvents;
if (events) {
allowedEvents = ['close', 'error', 'complete'].concat(events);
}
this.on = function(event, fn) {
attach(listeners, event, fn, allowedEvents);
return this;
};
this.off = function(event, fn) {
remove(listeners, event, fn);
return this;
};
this.close = function(reason) {
close(reason);
return this;
};
this.error = function(reason) {
error(reason);
return this;
};
}
module.exports = _implements(Stream, StreamImpl);