3

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?

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Buncha
  • 51
  • 5
  • Well, you're delaying the define by 1 second and require is trying to request it before that timer has expired. Can I ask why you're delaying the define module? – Simon Smith May 06 '12 at 11:59
  • It's just one of possible cases. Delay may be caused by ajax request or any other async process, needed for module to become ready. – Buncha May 06 '12 at 13:56
  • It would make more sense to create a module that is responsible for your Ajax/async logic. That way you can just require it, and use the methods it provides to trigger any async stuff. – Simon Smith May 06 '12 at 16:20
  • Hi Buncha, I tried delaying the call of define() too, because I wanted to simulate retrieving the the module over a slow internet connection. Perhaps this isn't the way to do it? – Michael R May 25 '13 at 23:53
  • Michael, I still have no solution for delaying define(). But i have advice for you: pack your module into server-side script and just use its sleep() function before sending module. – Buncha May 27 '13 at 05:31

1 Answers1

0

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.

Gabriel Jürgens
  • 3,055
  • 3
  • 20
  • 19
  • Thanks, I've done it like this already. But I tried to define in way, when the require-side knows nothing about delay... – Buncha May 09 '12 at 09:55