Reputation: 13
Running require(['pages/home'])
will work once but if I use require(['pages/home'])
again then it won't run.
The module "pages/home" is a file named "home.js" in a directory named "pages".
main.js
require(['pages/home']);
pages/home.js
define('pages/home', function() {
console.log('running pages/home module');
});
Upvotes: 1
Views: 765
Reputation: 462
Make it return a function/object that can be executed after you require it.
define('pages/home', function() {
return function(){
console.log('running pages/home module');
};
});
require(['pages/home'], function(resultFunc){
window.YourFunc = resultFunc;
});
Now you can execute your function whenever you want
Upvotes: 0
Reputation: 48267
Static code in modules isn't supposed to be evaluated more than once, just like a script loaded through a normal <script>
tag won't be run more than once during the page load.
Imagine if a module contained code like:
define('my-module', function () {
var foo = foo || 0;
var bar = ++foo;
});
You should expect bar
and foo
to both === 1
, but if the module was run repeatedly and a global foo
existed, that may not be the case. Admittedly, this is a very contrived example, but evaluating a module repeatedly could cause serious problems.
Upvotes: 0
Reputation: 151401
RequireJS modules are singletons. It loads a module once and only once. If a module has been loaded already, what you get if you load it again is a reference to the same module as originally loaded. The factory function you pass to define
won't be run a second time.
So what you are seeing is exactly what is expected.
Upvotes: 4