Skip to content

Instantly share code, notes, and snippets.

@adorsk
Created July 27, 2012 19:47
Show Gist options
  • Save adorsk/3190138 to your computer and use it in GitHub Desktop.
Save adorsk/3190138 to your computer and use it in GitHub Desktop.
jQuery Action Queue Sketch
require([
"jquery",
"use!backbone",
"use!underscore",
"_s",
"use!ui",
],
function($, Backbone, _, _s, ui){
var actionSet = {
//async: false,
async: true,
actions: [
{
type: 'action',
def: {
type: 'log',
opts: {
msg: "Action1",
delay: 500
}
}
},
{
type: 'action',
def: {
type: 'log',
opts: {
msg: "Action2",
delay: 200
}
}
}
]
};
// Takes an action definition, and returns an
// action function.
var processActionDef = function(actionDef){
var action = null;
if (actionDef.type == 'log'){
action = function(){
var deferred = $.Deferred();
setTimeout(function(){
console.log("logging, ", actionDef.opts.msg);
deferred.resolve();
}, actionDef.opts.delay);
return deferred;
};
};
return action;
};
var processActionSetDef = function(actionSetDef){
var action = function(){
var deferred = $.Deferred();
// Assemble actions from definitions.
var sub_actions = [];
_.each(actionSetDef.actions, function(item){
if (item.type == 'action'){
var sub_action = processActionDef(item.def);
sub_actions.push(sub_action);
}
else if (item.type == 'actionSet'){
console.log('actionSet');
}
});
// If there were sub actions...
if (sub_actions.length > 0){
// Deferred representing final sub deferred.
var final_sub_deferred = null;
// If async, execute actions in parallel.
if (actionSetDef.async){
console.log("async");
var sub_deferreds = [];
_.each(sub_actions, function(sub_action){
var sub_deferred = sub_action();
sub_deferreds.push(sub_deferred);
});
final_sub_deferred = $.when.apply($, sub_deferreds);
}
// Otherwise, execute actions in sequence.
else{
// Initialize w/ first subaction.
final_sub_deferred = sub_actions[0]();
// Trigger subsequent subactions in sequence.
for (var i = 1; i < sub_actions.length; i++){
var i_ = i;
final_sub_deferred = final_sub_deferred.pipe(function(){
return sub_actions[i_]();
});
}
}
// When final deferred is complete, resolve.
final_sub_deferred.done(function(){
deferred.resolve();
});
}
// If there were no sub actions, resolve immediately.
else{
deferred.resolve();
}
return deferred;
};
return action;
};
$(document).ready(function(){
console.log("document.ready");
var action = processActionSetDef(actionSet);
var dfd = action();
dfd.done(function(){
console.log("all done");
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment