我试图让鸣叫从一个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]
的,我很接近,但仍缺少的东西。
这可能是一个愚蠢的问题,而是你做了'(新TweetsView())。渲染()'? – 2012-01-11 20:22:21
是的(不是一个愚蠢的问题:)。我意识到现在我离开了解析函数,我添加了它(更新了上面的代码),但是当我登录到控制台时仍然获得一个空数组[]。 – jbnunn 2012-01-11 20:26:08
当你调用render()时,你应该在firebug中看到一个GET请求。那里的回应是什么? – 2012-01-11 20:30:51