Skip to content

Instantly share code, notes, and snippets.

@ryan953
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryan953/13cec75f9a4a8011be7f to your computer and use it in GitHub Desktop.
Save ryan953/13cec75f9a4a8011be7f to your computer and use it in GitHub Desktop.
Bootloaded Event Queue
// some module that might not be loaded on the page right away.
var Something = {
handleClick: function(e) {
console.log(+new Date(), 'click handled', e);
}
};
// (fake) fancy dynamic bootloader to get modules on the fly
var Bootloader = {
things: [],
register: function(name, thing) {
this.things[name] = thing;
},
require: function(name, callback) {
var _this = this;
console.log(+new Date(), 'will return', name, 'after 1000ms');
setTimeout(function() {
console.log(+new Date(), 'times up, returning', name);
return callback(_this.things[name]);
}, 1000); // Always takes 1000ms to look up a module
}
};
Bootloader.register('Something', Something);
// The MAGIC Starts here (prototype class)
var EventQueue = {
buffers: {},
loaders: {},
dequeue: function(bufferName, obj, method) {
var buffer = EventQueue.buffers[bufferName];
var fn = EventQueue.loaders[obj][method];
while(buffer && buffer.length) {
fn(buffer.shift());
}
},
queue: function(name, obj, method) {
return function(e) {
if (!EventQueue.buffers[name]) {
EventQueue.buffers[name] = [];
}
EventQueue.buffers[name].push(e);
var savedObj = EventQueue.loaders[obj];
if (!savedObj) {
console.log(+new Date(), 'Bootloading', obj, 'will queue until then');
EventQueue.loaders[obj] = true;
Bootloader.require(obj, function(LoadedObj) {
console.log(+new Date(), obj, 'is loaded, draining the queue');
EventQueue.loaders[obj] = LoadedObj;
EventQueue.dequeue(name, obj, method);
});
}
if (savedObj) {
if (savedObj === true) {
console.log(+new Date(), 'already bootloaded', obj, 'wait please');
} else { // if it's an object or method then call it
EventQueue.dequeue(name, obj, method);
}
}
};
}
};
// This is the client API that people would actually use within react:
// `<a onClick={EventQueue.queue('primaryEvent', 'Something', 'handleClick')}>Click here</a>`
var myEventListener = EventQueue.queue('primaryEvent', 'Something', 'handleClick');
// END client API
// prep some fake click events
var i = 0;
var triggerClick = function() {
var browserEventPayload = {
count: i++,
time: +new Date()
};
myEventListener(browserEventPayload);
};
// simulate some button clicks
setTimeout(triggerClick, 0);
setTimeout(triggerClick, 300);
setTimeout(triggerClick, 600);
setTimeout(triggerClick, 900);
setTimeout(triggerClick, 1200);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment