v86/src/bus.js

105 lines
1.8 KiB
JavaScript
Raw Normal View History

"use strict";
var Bus = {};
/** @constructor */
function BusConnector()
{
this.listeners = {};
this.pair = undefined;
2019-02-23 16:41:03 +01:00
}
2015-01-09 04:21:01 +01:00
/**
* @param {string} name
2019-02-23 16:41:03 +01:00
* @param {function(?)} fn
2015-01-09 04:21:21 +01:00
* @param {Object} this_value
2015-01-09 04:21:01 +01:00
*/
BusConnector.prototype.register = function(name, fn, this_value)
{
var listeners = this.listeners[name];
if(listeners === undefined)
{
listeners = this.listeners[name] = [];
}
listeners.push({
fn: fn,
2015-01-09 04:21:21 +01:00
this_value: this_value,
});
};
2015-01-09 04:21:01 +01:00
/**
* Unregister one message with the given name and callback
*
* @param {string} name
* @param {function(?)} fn
2015-01-09 04:21:01 +01:00
*/
BusConnector.prototype.unregister = function(name, fn)
2015-01-09 04:21:01 +01:00
{
var listeners = this.listeners[name];
if(listeners === undefined)
{
return;
}
this.listeners[name] = listeners.filter(function(l)
{
2019-02-23 16:41:03 +01:00
return l.fn !== fn;
2015-01-09 04:21:01 +01:00
});
};
2014-12-26 20:36:58 +01:00
/**
2015-01-06 20:22:42 +01:00
* Send ("emit") a message
*
2014-12-26 20:36:58 +01:00
* @param {string} name
2015-02-25 18:21:54 +01:00
* @param {*=} value
* @param {*=} unused_transfer
2014-12-26 20:36:58 +01:00
*/
BusConnector.prototype.send = function(name, value, unused_transfer)
{
if(!this.pair)
{
return;
}
var listeners = this.pair.listeners[name];
if(listeners === undefined)
{
return;
}
for(var i = 0; i < listeners.length; i++)
{
var listener = listeners[i];
2015-01-09 04:21:21 +01:00
listener.fn.call(listener.this_value, value);
}
};
2015-01-06 20:22:42 +01:00
/**
* Send a message, guaranteeing that it is received asynchronously
*
* @param {string} name
* @param {Object=} value
*/
BusConnector.prototype.send_async = function(name, value)
2015-01-06 20:22:42 +01:00
{
dbg_assert(arguments.length === 1 || arguments.length === 2);
setTimeout(this.send.bind(this, name, value), 0);
};
Bus.create = function()
{
var c0 = new BusConnector();
var c1 = new BusConnector();
c0.pair = c1;
c1.pair = c0;
return [c0, c1];
};