Roukmoute
Roukmoute

Reputation: 779

Backbone _.each collection.model empty

I'm trying to simply return what I request in PHP to JSON. My problem is that each Stock is not yet completed. Indeed, it is the "render" but "this.collection.models" is not yet completed because the request is not yet finished.

What should I do to correct this problem, wait until the request is finished so that the loop is done correctly.

Thank you in advance

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 () {
        ;
    }
});

Upvotes: 2

Views: 3024

Answers (1)

jakee
jakee

Reputation: 18556

You render before the fetch is done. What you want to do, is to wait for the fetch to complete and then render. Now how would you get notification of when the fetch is done? You have 2 options:

The success function (Not recommended by me)

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

Now when the fetch has been successful, render is called. This however can cause scoping problems and Backbone.js offers a much nicer alternative to callback functions: events.

Event callback (prefer this)

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

Upvotes: 7

Related Questions