How to wait till require finished in dojo

♀尐吖头ヾ 提交于 2019-12-06 14:00:33

问题


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 ?


回答1:


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);



回答2:


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();


来源:https://stackoverflow.com/questions/17406681/how-to-wait-till-require-finished-in-dojo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!