bitcore-node-zcash/lib/bus.js

85 lines
2.2 KiB
JavaScript
Raw Normal View History

2015-07-29 10:36:23 -07:00
'use strict';
var events = require('events');
var util = require('util');
2015-09-22 08:38:14 -07:00
/**
* The bus represents a connection to node, decoupled from the transport layer, that can
* listen and subscribe to any events that are exposed by available services. Services
* can expose events that can be subscribed to by implementing a `getPublishEvents` method.
* @param {Object} params
* @param {Node} params.node - A reference to the node
*/
2015-07-29 10:36:23 -07:00
function Bus(params) {
events.EventEmitter.call(this);
2015-08-28 13:16:51 -07:00
this.node = params.node;
2015-07-29 10:36:23 -07:00
}
util.inherits(Bus, events.EventEmitter);
2015-09-22 08:38:14 -07:00
/**
* This function will find the service that exposes the event by name and
* call the associated subscribe method with the arguments excluding the
* first argument of this function.
* @param {String} name - The name of the event
*/
2015-07-29 10:36:23 -07:00
Bus.prototype.subscribe = function(name) {
2015-08-31 06:00:00 -07:00
var events = [];
2015-08-06 13:19:36 -07:00
2015-08-31 06:00:00 -07:00
for(var i in this.node.services) {
var service = this.node.services[i];
events = events.concat(service.getPublishEvents());
2015-08-06 13:19:36 -07:00
}
for (var j = 0; j < events.length; j++) {
var event = events[j];
var params = Array.prototype.slice.call(arguments).slice(1);
params.unshift(this);
if (name === event.name) {
event.subscribe.apply(event.scope, params);
2015-07-29 10:36:23 -07:00
}
}
};
2015-09-22 08:38:14 -07:00
/**
* The inverse of the subscribe method.
* @param {String} name - The name of the event
*/
2015-07-29 10:36:23 -07:00
Bus.prototype.unsubscribe = function(name) {
2015-08-31 06:00:00 -07:00
var events = [];
2015-08-06 13:19:36 -07:00
2015-08-31 06:00:00 -07:00
for(var i in this.node.services) {
var service = this.node.services[i];
events = events.concat(service.getPublishEvents());
2015-08-06 13:19:36 -07:00
}
for (var j = 0; j < events.length; j++) {
var event = events[j];
var params = Array.prototype.slice.call(arguments).slice(1);
params.unshift(this);
if (name === event.name) {
event.unsubscribe.apply(event.scope, params);
2015-07-29 10:36:23 -07:00
}
}
};
2015-09-22 08:38:14 -07:00
/**
* This function will unsubscribe all events.
*/
2015-08-03 13:35:38 -07:00
Bus.prototype.close = function() {
2015-08-31 06:00:00 -07:00
var events = [];
2015-08-06 13:19:36 -07:00
2015-08-31 06:00:00 -07:00
for(var i in this.node.services) {
var service = this.node.services[i];
events = events.concat(service.getPublishEvents());
2015-08-06 13:19:36 -07:00
}
// Unsubscribe from all events
for (var j = 0; j < events.length; j++) {
var event = events[j];
event.unsubscribe.call(event.scope, this);
}
2015-08-03 13:35:38 -07:00
};
2015-07-29 10:36:23 -07:00
module.exports = Bus;