Reputation: 1117
I have 3 modules : Module A, Module B and Module C.
Module A writes links in my html page (the links come from an ajax async call) Module B writes some links too. In my module C, I would like to add an event on the links from module A and B.
The problem is the module loading order is random. So, when module C is loaded in first, there is no link because Module A and B didn't write yet.
Is there a way to load the module C at the end ?
Thank's
Upvotes: 0
Views: 1994
Reputation: 15104
Module load order should not matter. E.g.
define(function() {
return { addLinks: function() { ... } };
})
define(function() {
return { addLinks: function() { ... } };
})
define(function() {
return { addEvents: function() { ... } };
})
require(["links1", "links2", "events"], function(links1, links2, events) {
links1.addLinks(...);
links2.addLinks(...);
events.addEvents(...);
});
In other words, don't have your modules execute something when they load, have them return methods that can be executed when you are ready.
The modules above can load in any order ...
and it does not matter.
EDIT - If links1
uses XHR, then app
needs to wait for those links before adding them.
define(function() {
var promise = null;
function loadLinks() {
if (promise) {
return promise;
}
return promise = $.ajax(...).then(function(data) {
return convertDataToLinks(data);
});
}
return {
loadLinks: loadLinks,
addLinks: function() { ... }
};
})
require(["links1", "links2", "events"], function(links1, links2, events) {
links1.loadLinks().then(function(links) {
links1.addLinks(links);
links2.addLinks(links);
events.addEvents(...);
});
});
Upvotes: 2