Trunk, RequireJS and Tree

I am rewriting the category tree view in the RequireJS and Backbone application.

The structure is simple: each category contains a set of child categories.

However, the problem of circular dependence becomes apparent. A category model requires a set of categories, and a category model requires a category model.

RequireJS docs have a brief description of circular dependency:

http://requirejs.org/docs/api.html#circular

However, it seems that I am missing something because I am still getting vague and / or errors. I think that just seeing “b,” and not “a” in the examples does not allow me to understand.

Can anyone provide a simple example that can be clarified? This is or the best way of structuring, which does not require cyclical dependence.

+4
source share
1 answer

Due to the circular reference, when require.js loads “b” as a prerequisite for “a”, it cannot return the value “a” because initModule() has not yet been called. However, by the time b.somethingElse() called, module "a" was initialized, and the call to require("a") would return.

The following code shows that inside both modules, the order in which they are loaded does not matter. I slightly modified it from the require.js example to make it more obvious.

 // Inside a.js: define(["require", "b"], function initModule(require) { return { doSomehingWithA: function() { ...}, doSomethingElse: function(title) { // by the time this function is called, // require("b") will properly resolve return require("b").doSomethingWithB(); } } } ); // Inside b.js: define(["require", "a"], function initModule(require) { return { doSomethingWithB: function() {...}, doSomethingElse: function(title) { // by the time this function is called, // require("a") will properly resolve return require("a").doSomethingWithA(); } }; } ); 

By the way, while circular links are generally a symptom of poor design, this is not always the case. For example, I implemented a factory widget module, which, among other things, referenced the container-widget module, which then had to reference the factory in order to create its content. Completely legal.

+2
source

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


All Articles