I’m trying to get tweets to pull from a URL, which returns data in the form of:
[
{"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"}
]
I have a model,
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"
}
});
I have a collection,
window.Tweets = Backbone.Collection.extend(null,{
url: '/tweets/',
model: Tweet,
parse: function(response) {
return response.results;
}
});
and I have a view
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());
} ...
Both
alert(tweets.at(0));
and
alert(tweets.length)
give me “Undefined.” What am I missing?
EDIT
If I log the response (in the view), I do get something back:
[object Object],[object Object],[object Object]
so, I’m close, but still missing something.
Based on your comments, I would say the data is coming in right.
Try adding
console.log(response);in your parse function.In my backbone models, the parse() method just returns the first argument, which would be response in your case. I think you need to just change
to