RequireJS modules are single point. If you load main
once, twice, 10 times, you will always get the same module. And if you change its state, it will be changed for all modules that use it. You can specify RequireJS to define a module, but I do not recommend it, because it will just make your code unclear.
If I wanted to do what you are trying to do, I would develop my code something like this:
<script> define("main", [], function() { function Main (opt) { this.opt = opt; } return Main; }); define("plugin1", [], function() { return { install: function (main) { main.opt += " plugin1"; } }; }); define("plugin2", [], function() { return { install: function (main) { main.opt += " plugin2"; } }; }); // Case 1: no plugins require(["main"], function(Main) { var main = new Main("A"); console.log(main.opt); }); // Case 2: only plugin1 require(["plugin1", "main"], function (plugin1, Main) { var main = new Main("A"); plugin1.install(main); console.log(main.opt); }); // Case 3: only plugin2 require(["plugin2", "main"], function (plugin2, Main) { var main = new Main("A"); plugin2.install(main); console.log(main.opt); }); // Case 4: plugin1 and plugin2 require(["plugin1", "plugin2", "main"], function (plugin1, plugin2, Main) { var main = new Main("A"); plugin1.install(main); plugin2.install(main); console.log(main.opt); });
In principle, make the main
class common to all cases, which can be initialized during construction and which can be modified by plugins. Then each plugin can set itself to main
. The above code is a minimal illustration of how this can be done. In a real project, the final solution should be developed taking into account the specific needs of the project.
Louis source share