dingo-core-0.1.0: bundles/_bootstrap/bootstrap.js
/*
* Bootstrapping code.
*/
var Dingo;
Dingo = (function ($) {
"use strict";
var exports, encoders, decoders;
exports = {};
encoders = {};
decoders = {};
function getWidget(i) {
return $('#i' + i);
}
function encodeAll(encoders) {
var encodedState = {};
$.each(encoders, function (widgetId, encoder) {
var widget;
widget = getWidget(widgetId);
if (widget.length > 0) {
if (typeof encoder === 'function') {
encodedState[widgetId] = encoder.call(widget);
}
}
} );
return encodedState;
}
exports.addEncoder = function (id, encoderFunc) {
if (encoderFunc !== null) {
encoders[id] = encoderFunc;
}
};
exports.addDecoder = function (id, decoderFunc) {
if (decoderFunc !== null) {
decoders[id] = decoderFunc;
}
};
exports.setWidgetValue = function (id, json) {
var d = decoders[id];
if (typeof d === 'function') {
d.call(getWidget(id), json);
}
};
// Initialize event source for receiving updates.
function poll() {
var eventSource;
console.log("Starting event source...");
eventSource = new EventSource("poll");
eventSource.onmessage = function(msg) {
eval(msg.data);
};
}
// Set up the callback handler.
exports.callback = function (id) {
var encodedState;
// Go.
encodedState = encodeAll(encoders);
console.log("Performing callback", id);
console.log("Callback data: ", encodedState);
$.ajax({
error : function (xhr, status, err) {
console.log("Callback", id, " error ", err);
// FIXME: Handle errors appropriately.
},
success : function (data, status, xhr) {
console.log("Callback completed", data, status);
},
complete : function () {
// Start polling once the initial callback has been processed.
if (id === 0) {
poll();
}
},
data : { 'state' : JSON.stringify(encodedState) },
type : 'POST',
dataType : 'script',
url: '/callback/' + id
});
};
// Return the methods.
return exports;
}(jQuery));
/*
* Bootstrap.
*/
$(document).ready(function () {
// Start by invoking the bootstrap callback.
Dingo.callback(0);
});