Skip to content

Instantly share code, notes, and snippets.

@keithamus
Created November 22, 2012 12:20
Show Gist options
  • Save keithamus/4130885 to your computer and use it in GitHub Desktop.
Save keithamus/4130885 to your computer and use it in GitHub Desktop.
How to do Dependency Injection in RequireJS?
define([], function () {
return function HypotheticalHelperMethod() {
doSomeOtherStuff();
}
});
define(["helperMethod"], function (helperMethod) {
MyClass = function () {
this.init()
}
MyClass.prototype.init = function () {
helperMethod(1, 2, 3);
}
});
require(["helperMethod", "myClass"], function (helperMethod, myClass) {
describe("MyClass tests", function () {
it("calls `helperMethod` upon init", function () {
// here i need to spyOn helperMethod, but if I set helperMethod
// to a jasmime spy:
helperMethod = jasmine.createSpy("helperMethod");
// I've altered my reference, and MyClass still has the original
// HypotheticalHelperMethod function.
var instance = new MyClass();
expect(helperMethod).toHaveBeenCalledWith(1, 2, 3);
});
});
});
@jrburke
Copy link

jrburke commented Nov 23, 2012

Ah, OK. If you want to just cram in a modification after a module has been created but before listeners are given a reference to it, you can use the semi-private onResourceLoad API:

https://github.com/jrburke/requirejs/wiki/Internal-API:-onResourceLoad

Note this API is always subject to change. It has been stable for a while, but no guarantees for the future, even though I have no immediate plans to change it.

To modify the value passed to modules dependent on the current module, this would work:

requirejs.onResourceLoad = function (context, map, depArray) {
  var id = map.id,
    internalModule = context.registry[id],
    existingExport = context.defined[id];

    //modify existing export here

    //If the modification is a modification to the base export (like
    //if the export was a function) and not just a property
    //modification on the export, hard set the new module value:
    internalModule.exports = context.defined[id] = newExportValue;
};

This onResourceLoad definition should be done after require.js loads, but before any module loading is done, at least for modules that you want to intercept.

@hisapy
Copy link

hisapy commented Nov 19, 2014

@keithamus did you find a way to test that your helperMethod is called?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment