[英]In Backbone.js, how can I fetch data from a URL?
我正在尝试从URL提取推文,该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]
因此,我很接近,但仍然缺少一些东西。
根据您的评论,我会说数据正确无误。
尝试添加console.log(response);
在您的解析函数中。
在我的骨干模型中,parse()方法仅返回第一个参数,这将是您的情况下的响应。 我认为你需要改变
return response.results;
至
return response;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.