2015-06-14 168 views
0

我试图从静态json文件中提取数据,但数据根本没有显示出来。可能的原因是什么? 下面是我的代码:未从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")); 
    } 

回答

1

的问题是,这种代码:this.fetch()完成之前

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

最终被执行。你需要要么把你的代码this.fetchsuccess回调,像这样:

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(); 

你可以阅读更多关于骨干的事件系统和listenTo功能here

0

检查骨干分析功能。在获取之后,它也会调用vlidate并解析它们是否存在。

编辑:更详细

在这里,我想这是关键的东西,取()是异步的,所以你的时候开始循环,数据还没有实现。所以当你确定收集已经准备就绪时你需要执行代码。我通常会收听一个“重置”事件,并通过collection.fetch({reset:true})让抓取发起重置事件。

骨干收集,只要取,并在格式从服务器获取数据的阵列

[obj1,obj2], 

每一种将传递到一个解析函数,描述here

为您解决问题的目的简单地做:

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

这可以检查提取是否确实得到json。

在附注上,在初始化集合之后获取它总是一个好习惯,这意味着您不要将this.fetch()放入initialize()中,而是在外部执行此操作。

例如,如果你想打印出所有的元素名称,你可以做

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')); 
    }); 
} 

注意所有采集设置后,此“复位”事件触发,意味着它是在解析后()功能。除了这个parse(),还有一个由模型调用的验证函数。你的集合必须有一个模型参数,你可以制作自己的模型,并给它一个validate(),它也可以打印出东西。

+0

@EugenePodskal你说得对,当我看到这个问题时我很匆忙,并且谢谢你提醒我完成它。 – Evilsanta