Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Backbone.ajax to return data on success

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);
    }
});
like image 991
Jason Avatar asked Apr 12 '13 20:04

Jason


2 Answers

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);
    }
});
like image 89
JayC Avatar answered Sep 27 '22 19:09

JayC


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.

like image 25
hexacyanide Avatar answered Sep 27 '22 17:09

hexacyanide