How to wait till require finished in dojo

2019-04-16 10:15发布

I'm providing an infrastructure for other developers, and i'm using Dojo for it.

In my Init function i'm using the 'require' method (of course) which one of the parameters are the callback function when all the modules have been loaded.

The problem is that the client don't want to use callbacks. He wants to call me and line after to use me (to make my Init method synchronized) - and give him the code back after we for sure finished loading our modules.

My Code

<script src=..../dojo.js></script>

function Init()
{
   var loaded = false;

   require(["...myFiles..."], 
      function()
      {
          loaded = true;
      });

   // Whatever to do here or some other way to hold till the require operation finished
   while (!loaded) // :)
}

My Client side

  Init();
  myFiles.DoSomething();

Is it possible to do it ? To make require synchronized or do something else that waits till it's over ? To return from the init method only when the require method finished ?

2条回答
2楼-- · 2019-04-16 10:54

You can either call your next function from within the require response, or use a deferred object.

 function Init()
 {
    var d =  new dojo.Deferred();

    require(["...myFiles..."], 
       function()
       {
           d.resolve(true);
       });
   return d;
 }

Other file

 Init().then(myFiles.DoSomething);
查看更多
Luminary・发光体
3楼-- · 2019-04-16 10:57

Make your initializer be a module, say "my/Files", and make your init and doSomething functions be static methods of that module :

in "my/Files.js"

define([
    "dojo/_base/declare", 
    ...<your other required dependencies>
], function(declare){

    var myFiles = declare(null, {});

    myFiles.init = function(){
        // Your initialization code
    }

    myFiles.doSomething = function(){ ... }

    return myFiles;
});

In your html :

<script type="dojo/require">
    myFiles : "my/Files"
</script>

Then you can use it in your javascript like :

myFiles.init();
myFiles.doSomething();
查看更多
登录 后发表回答