Dependency Management Got Awesome
CommonJS and AMD Compliant dependency loader for modern web apps
Inject.addFetchRule
0.7.x
Inject.addFetchRule(matchesId, rule, options);
This function allows you to add a rule to use a loading mechanism other than the default Communicator object built in to Inject.
Examples
For a really complex example, see Inject’s Context File for how AMD support is achieved using the addFetchRule method.
// fetch a file using jQuery instead of Inject
RulesEngine.addFetchRule(/^.+?\!.+$/, function (next, content, resolver, communicator, info) {
var moduleName = info.moduleId;
var requestorName = info.parentId;
var requestorUrl = info.parentUrl;
var resolvedId = resolver.module(moduleName, requestorName);
var resolvedUrl = resolver.url(resolvedId, requestorUrl);
$.get(resolvedUrl)
.success(function(data) {
next(null, data);
});
matchesId
The matchesId
parameter can either be a string or a regex. If a string, an exact match on the Module ID is required in order to perform the fetch alternative. If matchesId
is a regular expression, then the Module ID is tested against the regex.
rule
The rule
parameter is a function with the following signature:
function(next, contents, resolver, communicator, info)
- next: A continuation function. A fetch rule must call
next()
to continue the loading process. Failure to do so will result in a fetch “hanging” and eventually timing out. Call next in the format ofnext(error || null, contents || null)
- contents: The contents up to this point. If a previous fetch function had data, this data is available in the contents argument.
- resolver: An object literal with two methods
resolver.module(id, relativeTo)
andresolver.url(path, relativeTo)
for resolving Module IDs and paths properly within the fetch function. For relative path resolution, many items needed are in theinfo
object. - communicator: An object literal with one method
get
which takes three parameters: moduleId, path, and a callback functionfunction(contents)
. This is a passthrough to Inject’s native communicator and can do standard cross domain communication. - info: An object literal containing data about the fetch function:
info.moduleId
: the current executing module’s IDinfo.parentId
: the parent of the current executing module’s IDinfo.parentUrl
: the resolved URL for the parent of the current executing module
options
A collection of options for this rule. Supported options are:
- weight: Assign a weight to this rule. Larger numbered rules run first.
The family of rules Inject supports: