I am trying to get the Backbone.ajax to return the collection "collection". I need the Model in another part of the program.
I would like to make the data available on the same level as the ajax method.
Backbone.ajax({
dataType: "jsonp",
url: "https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=twitterapi&count=25",
data: "",
success: function(val){ val
var Model = Backbone.Model.extend({});
var Collection = Backbone.Collection.extend({
model:Model
});
collection = new Collection(val);
console.log(collection);
}
});
Noooo! Your connection's existence should almost never be contingent on any "ajax" invocation! You need to move the collection's definition and instance outside of your ajax success method and somewhere before the ajax invocation, and then just
reset
oradd
the collection within the success method or something similar. You need it external so that you can define all of your view bindings, etc before you actually need the data; otherwise you end up with a big mess--one which you are trying to avoid by using Backbone.You can apply a callback to the function like so:
When the function is executed, it will wait for the callback to execute anything inside the function. Therefore, I'd suggest that you add a callback for the case in which the AJAX call fails.