2

我觉得我在这里遗漏了一些非常明显的东西。这是我的模型:

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

    return spamTermsModel;
});

这是使用该模型的集合:

define([
        'jquery',
        'underscore',
        'backbone',
        'models/spamTermsModel'
    ],
    function($, _, Backbone, spamTermsModel) {
        var spamTermsCollection = Backbone.Collection.extend({
            model: spamTermsModel,
            url: 'spam-terms',
            initialize: function(models, options) {
                //console.log(models);
                this.fetch({
                    success: function(data, options) {
                        //console.log(data);  // logs data correctly
                    }
                });
            }
        });

        return spamTermsCollection;
    }
 );

这是我称之为集合的视图:

define([
    'jquery',
    'underscore',
    'backbone',
    'models/spamTermsModel',
    'collections/spamTermsCollection'
], function($, _, Backbone, spamTermsModel, spamTermsCollection) {
    var searchTermsView = Backbone.View.extend({
        initialize: function() {
            var stm = new spamTermsModel();
            console.log(stm);  // returns function()
            this.collection = new spamTermsCollection();
            console.log(this.collection.toJSON());  // returns empty collection
        },
        retrieveTemplate: function(model) {
            return _.template($('#spamTermsTemplate').html(), model);
        },
        createList: function() {
            var list = '';
            _.each(this.collection.toJSON(), function (obj) {
                list += obj.term + ', ';
                //console.log(obj);
            });
            //console.log(this.collection.toJSON());
            return list;
        },
        render: function() {
            list = this.createList();
            this.$el.html(this.retrieveTemplate(list));
            return this;
        }
    });

    return searchTermsView;


   });
});

最后是我的路线:

router.on('route:updateSpamTerms', function() {
    require(['views/spamTermsView'], function(st) {
          s = new st();
          $('#web-leads').html(s.render().el);
    });

});

我认为问题出在我的模型中,因为它console.log()是函数()。我觉得它应该记录一个新模型。我尝试返回一个新模型,但我收到一个错误,即模型不是构造函数。我在这里想念什么?

4

1 回答 1

2

this.collection = new spamTermsCollection(); console.log(this.collection.toJSON()); // returns empty collection

这是因为您的 fetch 是异步的,并且您在成功获取之前尝试访问它。

您可以绑定到集合的reset事件并呈现您的集合视图。

this.collection.on('reset', this.render, this);

如果获取始终是异步的,这应该可以工作,但如果由于某种原因它不是将来,您可能会遇到问题。您可以考虑将 fetch 移出initialize以确保:

this.collection = new spamTermsCollection();
this.collection.on('reset', this.render, this);
this.collection.fetch();
于 2013-02-04T20:16:39.483 回答