Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining modules and using them immediately with RequireJS

I'm writing some tests for an application which is using RequireJS. Because of how the application works, it expects to get some classes via calling require. So, for testing, I have some dummy classes, but I don't want to have to put them into individual files just for this test. I'd much prefer to just define() them manually inside my test file like so:

define('test/foo', function () {
    return "foo";
});

define('test/bar', function () {
    return "bar";
});

test("...", function () {
    MyApp.load("test/foo"); // <-- internally, it calls require('test/foo')
});

The issue here is that the evaluation of those modules is delayed until a script onload event is fired.

From require.js around line 1600:

//Always save off evaluating the def call until the script onload handler.
//This allows multiple modules to be in a file without prematurely
//tracing dependencies, and allows for anonymous module support,
//where the module name is not known until the script onload event
//occurs. If no context, use the global queue, and get it processed
//in the onscript load callback.
(context ? context.defQueue : globalDefQueue).push([name, deps, callback]);

Is there some way I can manually trigger the queue to be evaluated?

like image 909
nickf Avatar asked Jan 16 '12 13:01

nickf


People also ask

What is a RequireJS module?

RequireJS loads each dependency as a script tag, using head. appendChild(). RequireJS waits for all dependencies to load, figures out the right order in which to call the functions that define the modules, then calls the module definition functions once the dependencies for those functions have been called.

Is RequireJS still relevant?

RequireJS has been a hugely influential and important tool in the JavaScript world. It's still used in many solid, well-written projects today.

What is the use of RequireJS?

RequireJS is a JavaScript library and file loader which manages the dependencies between JavaScript files and in modular programming. It also helps to improve the speed and quality of the code.

How do I call a function in RequireJS?

2 Answers. Show activity on this post. require(["jquery"], function ($) { function doStuff(a, b) { //does some stuff } $('#the-button'). click(function() { doStuff(4, 2); }); });


1 Answers

The best I've found so far is to asynchronously require the modules:

define("test/foo", function () { ... });
define("test/bar", function () { ... });

require(["test/foo"], function () {
    var foo = require('test/foo'),
        bar = require('test/bar');
    // continue with the tests..
});
like image 58
nickf Avatar answered Oct 10 '22 19:10

nickf