RequireJS: definition in callback

In my module, I want to defer the "define" call, but RequireJS starts the callback after the file is loaded, and not when the "defined" ... For example:

a.js:

require(['b'], function(b){
  console.log(b);
});

b.js:

define({'foo':'bar'});

This works as the expected record object {foo: bar}. But if I go "define" to a deferred function:

b.js:

setTimeout(function(){
  define({'foo':'bar'});
}, 1000);

then console.log (b) writes "null".

What's wrong?

+3
source share
1 answer

I think that any delay or delay should occur inside the definition function, or you can use some callback pattern, for example:

//a.js
require(['b'], function(b){
  b.getData(
    function(data) {
        console.log(data);
    }
  );
});

//b.js
define(function(){
    this.getData = function(callback) {
        setTimeout(function(_callback){
            return function() {
                _callback({'foo':'bar'});
            }
        }(callback), 1000);     
    }
    return this;
});

Using this template, you can set the callback function in a.js to handle the delayed response from b.js.

Hope this helps you.

0
source

All Articles