数据未从json文件中获取

时间:2015-06-14 17:58:43

标签: json backbone.js collections

我正在尝试从静态json文件中获取数据,但数据根本没有显示。可能的原因是什么呢? 以下是我的代码:

    var Collection =  Backbone.Collection.extend({
    url: "names_of_people.json",
    initialize: function() {
        this.fetch();
    }
  });

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

2 个答案:

答案 0 :(得分:1)

问题是这段代码:

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

最终在this.fetch()完成之前执行。您需要将代码置于this.fetch的{​​{1}}回调中,如下所示:

success

或通过收听var Collection = Backbone.Collection.extend({ url: '/data.json', initialize: function() { this.fetch({ success: function() { console.log(collections, 'the length ' + collections.length); for (var i = 0; i < collections.length; i++) { console.log('done ' + collections.at(i).get('name')); } } }); } }); var collections = new Collection(); 成功完成sync时发生的集合this.fetch事件。这种模式在Backbone应用程序中更常用。

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);
        for (var i = 0; i < collections.length; i++) {
            console.log('done ' + collections.at(i).get('name'));
        }
    }
});

var collections = new Collection();

您可以阅读有关Backbone的事件系统和listenTo函数here的更多信息。

答案 1 :(得分:0)

check backbone parse function. after fetch it will also call vlidate and parse if they exist.

EDIT: more detail

The key thing here I think is, the fetch() is asynchronous, so by the time you start loop, the data is not here yet. So you need to execute the code when you are sure the collection is ready. I usually listen to a "reset" event, and let the fetch to fire a reset event by collection.fetch({reset:true}).

Backbone Collection, whenever fetch, and get an array of data from server in a format

[obj1,obj2], 

it will pass each of these into a parse function, described here

For debug purpose you can simply do:

var MyCollection=Backbone.Collection.extend({
    parse:function(response){
        console.log(response);
        return response;
    }
})

This can check if the fetch indeed get the json.

On a side note, it is always a good practise to fetch it after you initialized the collection, means you don't put the this.fetch() inside initialize(), you do this outside.

for example, if you want to print out all the element name, you can do

var c=MyCollection();
c.fetch({reset:true}); // this will fire 'reset' event after fetch
c.on('reset',printstuff());
function printstuff(){
    _.forEach(c,function(e){
       console.log(e.get('name'));
   });
}

Note this 'reset' event fires after all the collection is set, means it is after the parse() function. Apart from this parse(), there is also a validate function that is called by model. You collection must have a model parameter, you can make your own model, and give it a validate(), it also print out stuff.