Unable to fetch data from Twitter RESTful API using Backbone.js Collection
I'm trying to learn to fetch data from a database using the Backbone.js Collection method: fetch().
The jsfiddle example is here.
The object's length returned is zero which means I'm not getting any result back. I can very easily obtain the json using jquery ajax开发者_JS百科 and Backbone.sync is apparently using the .ajax method too. May I know what's wrong?
You're running across two issues.
The first is that twitter's results (what you want to turn into backbone models) resides under a "results" property. To use this data, you need to override the parse method in the collection. This is the specific example used in the backbone docs:
http://documentcloud.github.com/backbone/#Collection-parse
The second issue is that the fetch() method is asynchronous, so that when you're getting the 'length' on the collection, its happening before the response comes back from twitter, so its still 0 length.
You need to set up an event handler to listen for the results of the "fetch" and THEN output the length:
var Tweet = Backbone.Model.extend();
var Tweets = Backbone.Collection.extend({
model: Tweet,
url: 'http://search.twitter.com/search.json?q=obama&callback=?',
parse: function(response) {
return response.results;
}
});
var tweets = new Tweets();
tweets.bind('reset', function(collection) {
alert(collection.length);
});
tweets.fetch();
精彩评论