Backbone.js collection.models没有显示,但在那里

时间:2012-04-07 04:15:46

标签: javascript json backbone.js underscore.js

我有一个视图,它正在对集合进行fetch()并从服务器返回一些模型。

ProductsView = Backbone.View.extend({

    initialize: function() {
        _.bindAll(this, 'render');
        this.collection = new ProductCollection();
        this.collection.fetch({data: {limit : this.options.limit}});

        console.log(this.collection);

        this.render();
    },
    render: function() {

        var template = _.template( $("#product-template").html(), this );
        $(this.el).html( template );
        return this;
    }
});

在上面的console.log中,我看到如下对象:

products.view.js:13
d
_byCid: Object
_byId: Object
length: 7
models: Array[7]
__proto__: x

models就在那里,但当我console.log(this.collection.models)时它只显示[],在模型中,是一个像这样的对象数组:

models: Array[7]
0: d
1: d
2: d
3: d
4: d
5: d
6: d

其中每个都有attributes,其中包含已返回的值。

我在使用this.collection.models或使用get()时无法显示模型的原因也不起作用。

非常感谢!

1 个答案:

答案 0 :(得分:6)

通常this.collection.fetch({data: {limit : this.options.limit}})是异步操作,因此下一行不一定要打印collection的正确内容。

相反,您应该使用success方法提供的errorfetch回调作为其options参数的一部分(或收听集合的change事件),像这样:

this.collection.fetch(
    { 
        data: { limit : this.options.limit },
        success : function(collection, rawresponse) { 
            // do something with the data, like calling render 
        }
    }
);

为了完整起见:

this.collection.on('change', function(){ // some handling of the data };
this.collection.fetch();

是基于事件的方法。