Chris
Chris

Reputation: 1587

Backbone.js collection not getting data from url

My collection isn't getting data from the url I pass it. The console reports {length: 0, models: Array[0], _byId: Object}. The JSON definately exists, otherwise it causes an error. What am I missing?

JS:

$(document).ready(function(){

    // Model
    var Article = Backbone.Model.extend({
        defaults: {
        title: '',
        body: ''
      }
    });

    // Collection
    var Articles = Backbone.Collection.extend({
        model: Article,
        url: 'http://local.headless.com/apps/test.json'
    });

    // View
    var ArticlesView = Backbone.View.extend({
        el: $("#article-container"),

        initialize: function(){
            this.collection = new Articles;
            this.collection.fetch();
            console.log(this.collection); // Nothing here
            this.render();
        },
        render: function(){
          //var template = _.template( $("#article-template").html(), {} );
          //this.$el.html(template(this.collection.toJSON()));

        },

  });


    var articleView = new ArticlesView();

});

JSON:

[{"title":"<a href=\"\/node\/2\" hreflang=\"en\">Basic Page 2<\/a>","body":"<p>This is basic page 2<\/p>"},{"title":"<a href=\"\/node\/1\" hreflang=\"en\">This is a basic page<\/a>","body":"<p>This is the content for basic page 1<\/p>"}]

Upvotes: 0

Views: 37

Answers (1)

benhowdle89
benhowdle89

Reputation: 37464

this.collection.fetch().then(function(){
    console.log(this.collection);
    this.render();
}.bind(this));

fetch is asynchronous, you need to wait for it to complete before checking it/rendering...

Upvotes: 1

Related Questions