2012-01-11 41 views
0

我试图让鸣叫从一个URL,它的形式返回数据拉:在Backbone.js中,我如何从URL获取数据?

[ 
    {"user":"someuser1","tweet":"this is a #tweet","date":"2011-09 02"}, 
    {"user":"someuser2","tweet":"and this is a #tweet","date":"2011-09 02"}, 
    {"user":"someuser3","tweet":"and this is another #tweet","date":"2011-09"} 
] 

我有一个模型,

window.Tweet = Backbone.Model.extend({ 
    initialize: function(){ 
    this.bind('change',function(){ 
    }) 
    }, 
    defaults: { 
    "user": "some-other-user", 
    "tweet": "this is some tweet", 
    "date" : "2012-01-06" 
    } 
}); 

我有一个集合,

window.Tweets = Backbone.Collection.extend(null,{ 
    url: '/tweets/', 
    model: Tweet, 
    parse: function(response) { 
     return response.results; 
    } 
}); 

,我有一个观点

window.TweetsView = Backbone.View.extend({ 
    el: $('#content-top'), 
    initialize: function(){ 
     this.model.bind('change',this.render,this); 
    }, 
    render: function() { 

     var TweetsCollection = Backbone.Collection.extend({ 
     model : Tweet, 
     url: '/tweets/', 
     parse: function(response) { 
      return response.results; 
     } 
     }); 

    var tweets = new TweetsCollection; 
    tweets.fetch(); 

    console.log(tweets.toJSON()); 

    } ... 

两个

alert(tweets.at(0)); 

alert(tweets.length) 

给我 “未定义”。我错过了什么?

编辑

如果我登录的响应(视图),我得到的东西回来:

[object Object],[object Object],[object Object] 

的,我很接近,但仍缺少的东西。

+0

这可能是一个愚蠢的问题,而是你做了'(新TweetsView())。渲染()'? – 2012-01-11 20:22:21

+0

是的(不是一个愚蠢的问题:)。我意识到现在我离开了解析函数,我添加了它(更新了上面的代码),但是当我登录到控制台时仍然获得一个空数组[]。 – jbnunn 2012-01-11 20:26:08

+0

当你调用render()时,你应该在firebug中看到一个GET请求。那里的回应是什么? – 2012-01-11 20:30:51

回答

1

根据你的意见,我会说数据是正确的。

尝试在您的分析功能中添加console.log(response);

在我的骨干模型中,parse()方法只是返回第一个参数,这将是您的情况下的响应。我想你需要只是改变

return response.results; 

return response; 
+0

这绝对是让我在Eric的某个地方,它记录了3个对象。紧接着,Backbone.js(0.5.3)抛出错误: Uncaught TypeError:对象不是函数 – jbnunn 2012-01-11 20:54:26

+1

发现问题,埃里克 - 感谢您的帮助。我在Collection构造函数中使用了一个名称空间模型,模型:App.Tweet,这是抛弃了。在我删除之后,这很好,现在我得到了我之后的回复。 – jbnunn 2012-01-11 21:07:55