dingo-core-0.0.3: bundles/_bootstrap/bootstrap.js
/*
* Bootstrapping code.
*/
var Dingo;
Dingo = (function () {
var encoders = {};
var 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;
}
function addEncoder(id, encoderFunc) {
if (encoderFunc !== null) {
encoders[id] = encoderFunc;
}
}
function addDecoder(id, decoderFunc) {
if (decoderFunc !== null) {
decoders[id] = decoderFunc;
}
}
function setWidgetValue(id, json) {
var d = decoders[id];
if (typeof d === 'function') {
d.call(getWidget(id), json);
}
}
// Long polling handler.
function poll() {
var delay = 0;
// Otherwise we start one...
console.log("Starting long polling...");
$.ajax({
error : function (xhr, status, err) {
if (err === 'timeout') {
delay = 0; // timeout means we need to retry immediately
} else {
delay = 15000; // don't hammer the server
}
},
success : function (data, status, xhr) {
// Start polling immediately again.
delay = 0;
},
complete : function () {
// Restart poll.
setTimeout(poll, delay);
},
timeout : 60000,
data : { },
type : 'GET',
dataType : 'script',
url: '/poll'
});
}
// Set up the callback handler.
function callback(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 { 'callback' : callback,
'addEncoder' : addEncoder,
'addDecoder' : addDecoder,
'setWidgetValue' : setWidgetValue
};
}());
/*
* Bootstrap.
*/
$(document).ready(function () {
// Start by invoking the bootstrap callback.
Dingo.callback(0);
});