Backbone _.each collection.model为空

Rou*_*ute 2 collections model backbone.js

我试图简单地将我在PHP中请求的内容返回给JSON.我的问题是每个股票尚未完成.实际上,它是"渲染",但"this.collection.models"尚未完成,因为请求尚未完成.

我该怎么做才能解决这个问题,等到请求完成后才能正确完成循环.

先感谢您

var Article = Backbone.Model.extend({});

var Articles = Backbone.Collection.extend({
    model:Article,
    url: function() {
        return _BASE_URL+'/sync/getLastArticles';
    },
    initialize:function () {
        this.fetch();
    }
});

var ArticlesView = Backbone.View.extend({
    template:$('#articles').html(),

    initialize:function () {
        this.collection = new Articles();
        this.render();
    },

    render:function () {
        console.log(this.collection);
        var that = this;
        _.each(this.collection.models, function (item) {
            console.log(item);
        }, this);
    },

    renderArticle:function () {
        ;
    }
});
Run Code Online (Sandbox Code Playgroud)

jak*_*kee 7

renderfetch完成之前.你想做的是等待fetch完成然后再完成render.现在,您将如何获得完成时间的通知fetch?你有2个选择:

成功功能(我不推荐)

// ArticlesView
initialize: function() {
  _.bindAll(this); // Don't forget to BIND
  this.collection = new Articles();
  this.collection.fetch({
    success: this.render
  });
}
Run Code Online (Sandbox Code Playgroud)

现在,当获取成功时,会render被调用.然而,这可能会导致范围问题,Backbone.js提供了一个更好的替代回调函数:事件.

事件回调(更喜欢这个)

// ArticlesView
initialize: function() {
  _.bindAll(this);
  this.collection = new Articles();
  this.collection.on('reset', this.render); // bind the reset event to render
  this.collection.fetch();
}
Run Code Online (Sandbox Code Playgroud)