Run action after loading all requirejs modules

There are several modules on the page:

// module 1 require(['signalr'], function(s) { s.subscribe('myhub1', function () { /* some code */ }); }); // module 2 require(['signalr'], function(s) { s.subscribe('myhub2', function () { /* some code 2 */ }); }); 

And there is a method that should be called after calling all the modules (all subscriptions are completed):

 require(['signalr'], fuinction (s) { s.connect(); }); 

A possible solution is to define the modules and write this:

 // module 1 define('module 1', ['signalr'], function(s) { s.subscribe('myhub1', function () { /* some code */ }); }); // module 2 define('module 2', ['signalr'], function(s) { s.subscribe('myhub2', function () { /* some code 2 */ }); }); require(['signalr', 'module 1', 'module 2'], fuinction (s) { s.connect(); }); 

But the problem is that different pages have different modules, say:

page1.cshtml: module 1

page2.cshtml: module 1, module 2

Therefore, I cannot write: require (['signalr', 'module 1', 'module 2'], fyinction (s) {s.connect ();}); because module 2 cannot be defined on page2.cshtml.

+6
source share
1 answer

It would be best to conditionally build an array and pass it to the require function, and then complete your completion in the callback, as you mentioned in the question.

 var modulesToLoad = []; // Build the array require(modulesToLoad, function (s) { s.connect(); }); 

If for some reason you cannot aggregate your calls into a single request, you will need to track the modules to load and run the completion check that all downloaded, and then run the cleaning code

 var checkIfLoaded = { myhub1 : false, myhub2 : false, myhub3 : false } function checkIfReady(s) { for (var prop in checkIfLoaded) { if ( ! checkIfLoaded[prop] ) { return false; } } // Completion code s.connect(); } require(['myhub1'], function(s) { checkIfLoaded.myhub1 = true; checkIfReady(s); }); require(['myhub2'], function(s) { checkIfLoaded.myhub2 = true; checkIfReady(s); }); 

By thinking about this, you can create an array of requirements

+3
source

Source: https://habr.com/ru/post/945921/


All Articles