我自己找到了解决方案。
感谢 IntoTheVoid 的回答,但我希望有类似 AMD 的解决方案。这意味着,不再是“污染”全局命名空间。
我的解决方案有 2 个关键:
“https://github.com/addyosmani/backbone-aura”来自 Addy Osmani,“https://github.com/amdjs/amdjs-api/wiki/AMD”来自异步模块定义 (AMD) API 规范。
规范说:“如果工厂是一个函数,它应该只执行一次。”
因此,如果一个 amd 模块在 Web 应用程序中被多次指定为依赖项,则该依赖项不仅是 NOT LOADED MULTIPLE TIMES,它也是 NOT EXECUTED MULTIPLE TIMES strong>,这对我来说是新事物。它只执行一次,并保留工厂函数的返回值。具有相同路径的每个依赖项具有相同的对象。这改变了一切。
因此,您只需定义以下 amd 模块:
define([], function() {
var app_registry = {};
app_registry.global_event_obj = _.extend({}, Backbone.Events);
app_registry.models = {};
return app_registry;
});
现在,在您想要共享资源的那些模块中,您将这个 app_registry 模块声明为依赖项并写入一个:
define(['jquery','underscore','backbone','app_registry'],
function ($, _, Backbone, app_registry){
var firstView = Backbone.View.extend({
initialize: function() {
_.bindAll (this, 'methodOne');
this.model.bind ('change', this.methodOne);
this.model.fetch();
},
methodOne: function() {
app_registry.models.abc = this.model;
}
...
在另一个方面:
define(['jquery','underscore','backbone','app_registry'],
function ($, _, Backbone, app_registry){
var secondView = Backbone.View.extend({
initialize: function() {
_.bindAll (this, 'methodTwo');
app_registry.global_event_obj.bind ('special', this.methodTwo);
},
methodTwo: function() {
app_registry. ...
}
...