Last active
August 29, 2015 14:09
-
-
Save james-gardner/3f526b69a84e48987ec0 to your computer and use it in GitHub Desktop.
Example application initializers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Initialization could be broken down into swappable blocks (which could be turned on or off). | |
* Point is, the init sequence is more controllable if it's broken out into phases/functions. | |
* | |
* This is how it's done within Marionette: | |
* https://github.com/marionettejs/backbone.marionette/blob/master/src/marionette.application.js | |
* | |
* http://jsfiddle.net/agoftkng/5/ | |
*/ | |
var App = function() { | |
this._initializers = []; | |
}; | |
App.prototype = { | |
addInitializer: function(initializer) { | |
if (_.isFunction(initializer)) { | |
this._initializers.push(initializer); | |
} | |
}, | |
start: function() { | |
var args = _.toArray(arguments); | |
_.each(this._initializers, function(init) { | |
return init.apply(this, args); | |
}, this); | |
} | |
}; | |
/** | |
* This is quite good until: | |
* | |
* a) You can no longer depend on the order of execution. | |
* b) Your initializer fires off an async request and you need to wait for that to finish before | |
* the next one kicks in. | |
*/ | |
App.prototype = { | |
addInitializer: function(initializer) { | |
if (_.isFunction(initializer)) { | |
this._initializers.push(initializer); | |
} | |
}, | |
_next: function() { | |
var func = this._initializers.shift(); | |
if (func) { | |
if (func.length === 1) { | |
func.call(this, this._next.bind(this)); | |
} else { | |
func(); | |
this._next(); | |
} | |
} else { | |
console.log('initialization complete'); | |
} | |
}, | |
start: function() { | |
this._next.call(this); | |
} | |
}; | |
var app = new App(); | |
app.addInitializer(function() { | |
console.log('just a normal initializer'); | |
}); | |
app.addInitializer(function() { | |
console.log('another normal initializer'); | |
}); | |
app.addInitializer(function(done) { | |
console.log('async initializer - waiting five seconds.'); | |
setTimeout(done, 5000); | |
}); | |
app.start(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Need to put a setTimeout fallback in place ... so if the async op fails it aborts the init sequence.