src/link.js
/*jslint indent:2, node:true, sloppy:true */
var util = require('./util');
/**
* A link connects two freedom hubs. This is an abstract class
* providing common functionality of translating control channels,
* and integrating config information.
* @class Link
* @implements Port
* @constructor
*/
var Link = function (name, resource) {
this.id = 'Link' + Math.random();
this.name = name;
this.resource = resource;
this.config = {};
this.src = null;
util.handleEvents(this);
util.mixin(this, Link.prototype);
};
/**
* Receive messages from the hub to this port.
* Manages startup, and passes others to 'deliverMessage' implemented
* in derived classes.
* @method onMessage
* @param {String} flow the channel/flow of the message.
* @param {Object} message The Message.
*/
Link.prototype.onMessage = function (flow, message) {
if (flow === 'control' && !this.controlChannel) {
if (!this.controlChannel && message.channel) {
this.controlChannel = message.channel;
util.mixin(this.config, message.config);
this.start();
}
} else {
this.deliverMessage(flow, message);
}
};
/**
* Register a handler to alert of errors on this port.
* @method addErrorHandler
* @param {Function} handler Method to call with errors.
*/
Link.prototype.addErrorHandler = function (handler) {
this.onError = handler;
};
/**
* Report an error on this link.
* @method onerror
* @param {Error} err The error that occurred.
*/
Link.prototype.onError = function (err) {
//Filled in by addErrorHandler
};
/**
* Emit messages to the the hub, mapping control channels.
* @method emitMessage
* @param {String} flow the flow to emit the message on.
* @param {Object} messgae The message to emit.
*/
Link.prototype.emitMessage = function (flow, message) {
if (flow === 'control' && this.controlChannel) {
flow = this.controlChannel;
}
this.emit(flow, message);
};
module.exports = Link;