tube
Version:
Experimental Resource Loader implementing using Server Sent Events
78 lines (60 loc) • 2.55 kB
JavaScript
var tube = (function() {
//= manifest
function Tube(endpoint, opts) {
// ensure we have opts
opts = opts || {};
// initialise the number of connections
this.multi = opts.multi || 2;
// initialise the separator
this.separator = opts.separator || String.fromCharCode(0x214B);
// initialise the event sources
this.sources = this.connect(endpoint);
}
Tube.prototype = {
/**
## connect(endpoint: String)
*/
connect: function(endpoint) {
var connections = [],
separator = this.separator;
// initialise the connections
for (var ii = 0; ii < this.multi; ii++) {
connections[ii] = new EventSource(endpoint + '?p=' + ii);
}
console.log(separator);
// handle connection behaviour
connections.forEach(function(connection) {
connection.addEventListener('exception', function(evt) {
console.log('received exception', evt.data);
}, false);
connection.addEventListener('resource', function(evt) {
var resource, script, text;
// parse the data
try {
resource = JSON.parse(evt.data);
// create a script tag
script = document.createElement('script');
// create a text node for the script content
script.appendChild(
document.createTextNode(resource.data.split(separator).join('\n'))
);
// add the script to the document
document.body.appendChild(script);
}
catch (e) {
}
});
connection.addEventListener('done', function(evt) {
console.log('received done', evt);
connection.close();
}, false);
});
return connections;
}
};
// mixin asevented
// asEvented.call(Tube.prototype);
return function(endpoint, opts) {
return new Tube(endpoint, opts);
};
}());