3

我正在重写一个试图使用 AMD 方法的 Backbone.js 应用程序。我已经下载了 AMD 版本的 Backbone 和 Underscore。我检查并调用了 jQuery、Backbone 和 Underscore。这是一个相当简单的项目,但由于某种原因,我的收藏不再传递给我的视图。我是 AMD 的新手。

这是我的模型:

define([
    'underscore',
    'backbone'
], function(_, Backbone) {
    var tableModel = Backbone.Model.extend({});
    return tableModel;
});

这是我的收藏:

define([
    'jquery',
    'underscore',
    'backbone',
    'models/tableModel'
],
function($, _, Backbone, tableModel) {
    var tablesCollection = Backbone.Collection.extend({
        url: this.url,  // passed into collection at runtime, so same code can process multiple sets of data
        model: tableModel,
        initialize: function(models, options) {
            if (options && options.url) {
                this.url = options.url;
            }
            this.fetch({
                success: function(data, options) {
                    if ($.isEmptyObject(data.models)) {
                        App.Collections.Tables.NoData(data);
                    }

                }
            });
        }
    });

    return tablesCollection;
});

这是我的看法:

define([
    'jquery',
    'underscore',
    'backbone',
    'models/tableModel',
    'collections/tablesCollection',
    'views/tableView'
],
function($, _, Backbone, tableModel, tablesCollection, tableView) {
    var tv = Backbone.View.extend({
        tagName: 'div',
        initialize: function() {
            console.log(this.collection);  // returns collection and undefined 
            this.collection.on('reset', this.render, this);  // errors: this.collection is undefined
        },
        render: function() {
            return this;
        }
    });

    return tv;
});

这里是视图和集合被实例化的地方:

define([
    'jquery',
    'underscore',
    'backbone',
    'models/tableModel',
    'collections/tablesCollection',
    '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'});
    $('#web-leads').html(tables.render().el);

});

为什么我会被function (){return c.apply(this,arguments)}退回console.log(tablesCollection)?就像集合没有被传入一样。这可能是路径问题吗?我的项目由一个js文件夹构成,其中包含名为collectionsmodels的子文件夹views。如果我console.log(this),我得到: 在此处输入图像描述

我的数据在那里,但这是我需要的吗?为什么我尝试收藏时没有得到我的收藏console.log

4

2 回答 2

0

不要tablesCollection直接使用。使用this.collection. 你已经用它初始化了视图

于 2013-01-29T17:55:06.243 回答
0

您看到的是函数 tablesCollection,即 Backbone.Collection.extend(...) 函数。

函数tablesCollection可能很好地传递到视图中。但是,您需要在将对象记录到控制台之前实例化对象,例如 new tablesCollection(null, {url: 'url'}),否则将显示扩展包装函数,这就是您现在所看到的。

于 2013-01-29T18:10:19.293 回答