访问require.js回调的返回值

时间:2012-11-12 15:21:21

标签: javascript return-value requirejs amd

我在一个文件中定义了如下模块

define(['mod1', 'mod2'], function (mod1, mod2) {

    var IndexView = Backbone.View.extend({

        ...

    });

    return new IndexView;

});

这需要在另一个文件(我的Backbone路由器文件)中使用以下

require(['src/views/index']);

我是否可以从路由器范围内访问返回的IndexView对象,而无需在我的应用程序命名空间中存储引用?

1 个答案:

答案 0 :(得分:3)

使用require.js传递Backbone视图/模型的实例将很快让您的生活变得非常不快乐。使模块仅返回视图/模型的定义会更容易,这样可以在同一范围内实例化它们。

因此,如果您使视图模块只返回定义:

// IndexView module
define(['dep1', 'dep2'], function (dep1, dep2) {

    var IndexView = Backbone.View.extend({

        ...

    });

    return IndexView;

});

然后,您可以在路由器中实例化它:

// our main requirejs function
requirejs(['path/to/indexview'], function (IndexView) {

    var AppRouter = Backbone.Router.extend({

        initialize: function () {

            // bind our IndexView to the router
            this.IndexView = new IndexView();

        }

    });

    // start the app
    var app = new AppRouter();

});

这样你的代码仍然是模块化的,带有Require.js,但你可以使用this传递路由器的范围。