Created
January 9, 2009 17:37
-
-
Save Inviz/45192 to your computer and use it in GitHub Desktop.
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
var DependencyManager = new Class({ | |
Implements: [Chain], | |
initialize: function(doc) { | |
var constructor = this.using.bind(this) | |
this.manager = this | |
this.document = $pick(doc, document) | |
if (!DependencyManager.aliases) DependencyManager.aliases = {} | |
if (!DependencyManager.dependencies) DependencyManager.dependencies = {} | |
this.loaded = [] | |
return $extend(constructor, this) | |
}, | |
using: function() { | |
var args = $A(arguments).flatten(); | |
var callback = args.getLast().run && args.splice(-1)[0] | |
var start = !this.$chain.length | |
this.setup(args, callback) | |
if (start) this.callChain() | |
return this | |
}, | |
setup: function(args, callback) { | |
var files = args.map(this.expand.bind(this)).flatten().filter(this.notLoaded.bind(this)) | |
files.each(function(file) { | |
this.chain(this.load.pass(file, this)) | |
}, this) | |
if (callback) this.chain(function() { | |
this.callChain() | |
callback(); | |
}.bind(this)) | |
return this | |
}, | |
notLoaded: function(arg) { | |
return !this.loaded.contains(arg) | |
}, | |
register: function() { | |
var deps = $A(arguments); | |
var alias = deps.shift() | |
var file = deps.shift() | |
DependencyManager.aliases[alias] = file | |
DependencyManager.dependencies[file] = deps | |
return this | |
}, | |
expand: function(file) { | |
if (DependencyManager.aliases[file]) file = DependencyManager.aliases[file] | |
if (file.match(/^[a-z0-9]$/i)) { | |
console.error(file, 'looks like alias, but it is not registered') | |
} | |
return (DependencyManager.dependencies[file] || []).map(this.expand.bind(this)).concat(file) | |
}, | |
load: function(file) { | |
this.loaded.push(file) | |
return Asset.javascript(file + "?" + Math.random(), { | |
onload: function() { | |
console.info('Now using', file) | |
this.callChain() | |
}.bind(this), | |
document: this.document | |
}) | |
} | |
}); | |
(function() { | |
var setup = function() { | |
if (!this.manager) this.manager = new DependencyManager(this.document) | |
} | |
Window.implement({ | |
using: function() { | |
setup.call(this) | |
this.manager.using.apply(this.manager, $A(arguments)) | |
}, | |
register: function() { | |
setup.call(this) | |
this.manager.register.apply(this.manager, $A(arguments)) | |
} | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment