55 lines
1.2 KiB
JavaScript
55 lines
1.2 KiB
JavaScript
/*
|
|
* © Mikko Ahlroth 2014
|
|
* WeeCRApp is open source software. For licensing information, please check
|
|
* the LICENCE file.
|
|
*/
|
|
|
|
/*
|
|
* The event queue allows attaching callbacks to event IDs coming from the
|
|
* backend. Callbacks can be one-shot or continuous.
|
|
*/
|
|
|
|
.pragma library
|
|
|
|
.import "uniqid.js" as UID
|
|
.import "debug.js" as D
|
|
|
|
var _pendingEvents = {};
|
|
|
|
function handleEvent(id, data) {
|
|
//D.d("Handling " + id);
|
|
//D.d(JSON.stringify(_pendingEvents));
|
|
if (id in _pendingEvents) {
|
|
var c = _pendingEvents[id];
|
|
c.callback(data);
|
|
|
|
if (c.isOneshot) {
|
|
delete _pendingEvents[id];
|
|
}
|
|
}
|
|
}
|
|
|
|
function addHandler(id, callback, isOneshot) {
|
|
_pendingEvents[id] = {
|
|
"callback": callback,
|
|
"isOneshot": !!isOneshot
|
|
};
|
|
}
|
|
|
|
// Send a command and execute callback when the response arrives
|
|
function command(command, callback) {
|
|
// If callback is null, don't add an ID
|
|
var read_write = !!callback;
|
|
|
|
if (read_write) {
|
|
var id = UID.get();
|
|
command = "(" + id + ") " + command;
|
|
|
|
//D.d("Adding handler for " + id);
|
|
addHandler(id, callback, true);
|
|
}
|
|
|
|
handleEvent("__weecrapp_send", command);
|
|
}
|
|
|
|
|