RequireJS: defining in callback

2k Views Asked by At

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

a.js:

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

b.js:

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

This works as expected writing object {foo:bar}. But if i move "define" to deferred function:

b.js:

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

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

What's wrong?

1

There are 1 best solutions below

1
On

I think that any delay or defer should happen inside the define function, or you could use some callback pattern like this:

//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 pattern you can set a callback function in a.js to handle the delayed answer from b.js.

Hope this helps you.