backbone.js - Data not being fetched from json file -


i trying fetch data static json file data not getting displayed @ all. possible reason it. below code:

    var collection =  backbone.collection.extend({     url: "names_of_people.json",     initialize: function() {         this.fetch();     }   });    collections = new collection();   console.log("the length "+collections.length);   (i=1;i<collections.length;i++)   {     console.log("done "+ collections.at(i).get("name"));   } 

the problem code:

console.log("the length "+collections.length); (i=1;i<collections.length;i++) {   console.log("done "+ collections.at(i).get("name")); } 

ends being executed before this.fetch() has completed. you'll need either put code in this.fetch's success callback, this:

var collection =  backbone.collection.extend({     url: '/data.json',     initialize: function() {         this.fetch({             success: function() {                 console.log(collections, 'the length ' + collections.length);                 (var = 0; < collections.length; i++) {                     console.log('done ' + collections.at(i).get('name'));                 }             }         });     } });  var collections = new collection(); 

or listening collection's sync event, occurs when this.fetch has completed successfully. pattern more commonly used in backbone applications.

var collection =  backbone.collection.extend({     url: '/data.json',     initialize: function() {         this.listento(this, 'sync', this.syncexample);         this.fetch();     },     syncexample: function() {         console.log(collections, 'the length ' + collections.length);         (var = 0; < collections.length; i++) {             console.log('done ' + collections.at(i).get('name'));         }     } });  var collections = new collection(); 

you can read more backbone's event system , listento function here.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -