简体   繁体   English

使用backbone.marionette和requireJs的Web应用程序的循环依赖关系

[英]Circular Dependencies for a web app using backbone.marionette and requireJs

I am in the following situation. 我遇到以下情况。

I am using requireJs to loads module and I don't want to use global variables. 我使用requireJs来加载模块,我不想使用全局变量。

The main.js is responsible to load the router. main.js负责加载路由器。
Then the router loads the app and the app loads several subApps. 然后路由器加载应用程序,应用程序加载几个subApps。

After everything has been initialised, the subApps needs the router for making router.navigate . 一切都已初始化后,子应用程序需要routerrouter.navigate

Here the schema: 架构:

main.js -> router -> app -> subApp -> router

Then I have a problem of Circular Dependencies and for that reason the router in subApp will be undefined. 然后我遇到循环依赖的问题,因此subApp中的路由器将是未定义的。

What is the best way to reorganise my code or to fix this problem? 重新组织代码或解决此问题的最佳方法是什么? Are there some example about this? 有关于此的一些例子吗?

the schema: 架构:

 main.js -> router -> app -> subApp -> router

is right. 是对的。

If you are using backbone.marionette , in order to access the router from the app and subApp, without using global var , you should start the app in router in this way: 如果您使用backbone.marionette ,为了从app和subApp访问路由器,而不使用global var ,您应该以这种方式在路由器中启动应用程序:


// router.js
YourApp.start(router: router);

// app.js
YourApp.addInitializer(function(options){
  // do useful stuff here
  var myView = new MyView({
    router: options.router
  });
  YourApp.mainRegion.show(myView);
});

Subapp可以引发路由器处理的事件,而不是明确依赖路由器

In my project, I use the following dependency: main.js -> app -> router -> subApp. 在我的项目中,我使用以下依赖项:main.js - > app - > router - > subApp。

In app.js, I create a single global variable that holds a pointer to my app: 在app.js中,我创建了一个包含指向我的app的指针的全局变量:

define([...], function(...) {
return {
  initialize: function() {
    window.MyApp = new Backbone.Marionette.Application();
    // ...
    MyApp.start();
  }
};
});

This makes it extremely easy to access my app's regions from anywhere, as well as store global state information in one name space. 这使得从任何地方访问我的应用程序区域变得非常容易,并且可以在一个名称空间中存储全局状态信息。

I tried doing it without the global app at first, but eventually gave up and found this approach to be a lot more flexible. 我一开始尝试没有全局应用程序,但最终放弃了,发现这种方法更加灵活。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM