Backbone.js - data not being populated in collection even though fetch is successful

后端 未结 2 992
野性不改
野性不改 2020-12-01 20:17

I am trying to populate a collection from a simple JSON file as part of learning backbone.js. But I can\'t get it to work.

The AJAX call is made (verified with Fire

相关标签:
2条回答
  • 2020-12-01 20:50

    fetch is asynchronous, your collection won't yet be populated if you immediately call render. To solve this problem, you just have to bind the collection reset event (sync event for Backbone>=1.0) to the view render :

    theView = Backbone.View.extend({
       el: $("#temp"),
    
       initialize: function () {
           this.collection = new theCollection();
    
           // for Backbone < 1.0
           this.collection.on("reset", this.render, this);
    
           // for Backbone >= 1.0
           this.collection.on("sync", this.render, this);
    
           this.collection.fetch();
       },
    
       render : function () {
        console.log( this.collection.toJSON() );
       }
    });
    

    Note the third argument of the bind method, giving the correct context to the method: http://documentcloud.github.com/backbone/#FAQ-this

    0 讨论(0)
  • 2020-12-01 20:58

    i believe the problem lies in your json

    either you override the parse method on the collection, to work with your json

    or you could change the json :)

    [{
        "description": "Lorem ipsum..."
    },
    {
        "description": "Lorem ipsum..."
    }]
    

    i believe this is what your json should look like, just an array of your models.

    0 讨论(0)
提交回复
热议问题