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
or add
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.
//definitions
var MyModel = Backbone.Model.extend({});
var MyCollection = Backbone.Collection.extend({
model:Model
});
//wherever you need a collection instance
collection = new MyCollection();
//wherever you need to do the ajax
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){
collection.add(val); //or reset
console.log(collection);
}
});
You can apply a callback to the function like so:
function ajaxCall(callback) {
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) {
var Model = Backbone.Model.extend({});
var Collection = Backbone.Collection.extend({
model: Model
});
collection = new Collection(val);
callback(collection);
}
});
}
ajaxcall(function (collection) {
//do something with the collection when the callback is returned
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With