Load data into a Backbone collection from JSON file?

后端 未结 4 1913
执笔经年
执笔经年 2020-12-09 09:52

I\'m trying to load some data into a Backbone Collection from a local JSON file, using this very basic code:

  window.Student = Backbone.Model.extend({
  })         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-09 10:30

    I/O operations in javascript are almost always asynchronous, and so it is with Backbone as well. That means that just because AllStudents.fetch has returned, it hasn't fetched the data yet. So when you hit your console.log statement, the resources has not yet been fetched. You should pass a callback to fetch:

    AllStudents.fetch({ url: "/init.json", success: function() {
        console.log(AllStudents);
    }});
    

    Or optionally, use the new promise feature in jQuery (fetch will return a promise):

    AllStudents.fetch({ url: "/init.json" }).complete(function() {
        console.log(AllStudents);
    });
    

提交回复
热议问题