RequireJS / Backbone:获取从require返回的视图

时间:2013-01-30 19:46:44

标签: backbone.js requirejs amd

以下是我的观点:

define([
    'jquery',
    'underscore',
    'backbone',
    'models/tableModel',
    'collections/tablesCollection',
    'views/tablesView'
], function($, _, Backbone, tableModel, tablesCollection, tablesView) {
    require(['collections/tablesCollection'], function(tablesCollection) {
        var t = new tablesCollection(null, {url: 'main-contact'});
        var tables = new tablesView({ collection: t, template: 'main-contact-template'});
        tables.url = 'main-contact';
        return tables;  // <!-- returns view, tables can be console.log'ed
    });

    console.log(tables); // <!-- tables is not defined
});

如何在tables声明中获取require,以便console.log可以访问?这似乎是我需要返回视图的地方,所以我可以在我的路线中使用它:

app_router.on('route:index', function(){
        require(['views/tables/mainContactView'], function(mainContactView) {
            console.log(mainContactView);  // <!-- undefined, unless some value is returned from where the console.log() is above
            $('#web-leads').html(mainContactView.render().el);
        });
    });

如果我将return 'test'放在console.log(tables)所在的位置,我可以console.log()在我的路线中。所以我假设我需要从中返回视图。如何传出该数据?现在,即使有一个return语句,我的观点也是未定义的。我需要从require中获取视图。我该怎么做?

1 个答案:

答案 0 :(得分:0)

您已经在“定义”中加载了collection/tablesCollection,因此您无需另外执行require来加载它。

你可以简单地定义视图:

define([
    'jquery',
    'underscore',
    'backbone',
    'models/tableModel',
    'collections/tablesCollection',   // You've already required tablesCollection here.
    'views/tablesView'
], function($, _, Backbone, tableModel, tablesCollection, tablesView) {
    var t = new tablesCollection(null, {url: 'main-contact'});
    var tables = new tablesView({ collection: t, template: 'main-contact-template'});
    tables.url = 'main-contact';
    return tables;
});