Created
November 22, 2012 12:20
-
-
Save keithamus/4130885 to your computer and use it in GitHub Desktop.
How to do Dependency Injection in RequireJS?
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
define([], function () { | |
return function HypotheticalHelperMethod() { | |
doSomeOtherStuff(); | |
} | |
}); | |
define(["helperMethod"], function (helperMethod) { | |
MyClass = function () { | |
this.init() | |
} | |
MyClass.prototype.init = function () { | |
helperMethod(1, 2, 3); | |
} | |
}); |
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
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); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
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.