Skip to content

Instantly share code, notes, and snippets.

@jcreamer898
Last active December 17, 2015 22:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcreamer898/5685754 to your computer and use it in GitHub Desktop.
Save jcreamer898/5685754 to your computer and use it in GitHub Desktop.
A way to adjust the module context in require.js
require(['jquery', 'underscore'], function($, _) {
require.s.contexts._.execCb = function(name, callback, args) {
return callback.apply({
$: $,
_: _
}, args);
};
// init app here
});
@jrburke
Copy link

jrburke commented May 31, 2013

Maybe more background would help, but initial thoughts:

It is not very portable, and could have race issues if some other module that needs this change done.

I would prefer just exporting $ and _ as globals, or specifying those things as explicit dependencies in the module that uses them.

@jcreamer898
Copy link
Author

@jrburke Thanks for the comment!

The idea came from a friend of mine asking how to attach $ and _ to this inside of a module's factory function since as of now it just refers to the window.

I suppose if someone really wanted to do it like this and avoid the race condition they could init the app after redefining the execCb.

I wanted to make sure that the approach wouldn't rip a hole in the space time continuum... 😉

@ifandelse
Copy link

@jcreamer898 - forgive me for "C-ing" my way into an "A, B" conversation....just happened to see James's reply. Having worked on a couple of large require.js efforts, I can say that having these kinds of dependencies injected as normal deps into the module is a huge help, vs sneaking them in magically - since you can see the dep list of a module quite quickly, and be assured that no other secret deps were lurking that weren't in the list. (Of course you can always have 'secret' deps hanging off the window - but you have to decide how to address that as a team...to allow or not allow modules to touch the window directly...and follow the convention consistently). Going the "inject as normal dep" route more clearly expresses the intent, and doesn't lean in the direction of trampling on open/closed (a dilemma we js devs can fall into a lot b/c of our ability to monkey patch all the things). Just food for thought.

@jcreamer898
Copy link
Author

LOL @ifandelse I somehow JUST saw this comment. Epic gif is epic.

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