Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
98
rated 0 times [  104] [ 6]  / answers: 1 / hits: 20990  / 11 Years ago, fri, april 12, 2013, 12:00:00

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);
}
});

More From » json

 Answers
9

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);
}
});

[#78941] Thursday, April 11, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
muhammadbrandend

Total Points: 670
Total Questions: 95
Total Answers: 97

Location: Saint Vincent and the Grenadines
Member since Sat, Sep 11, 2021
3 Years ago
;