0

我修改了我的集合覆盖 fetch 方法,但 fetch 什么也不返回。

var Friendscollection = Backbone.Collection.extend({


model:Person,
url:"https://api.parse.com/1/classes/_User/",
idAttribute: "objectId",
parse: function(data) {

    return data.results;
},



initialize:function(){

   },

fetch: function(options) {
        var cur_user= Parse.User.current().id;           
          var res;  
     var ajax = $.ajax;        
   $.ajax({
//query rest che trova tutti gli amici dell'utente corrente        
type: 'GET',
async: false,
headers: {'X-Parse-Application-Id':'qS0KLM--h***PiTS3VMk','X-Parse- 
REST-API-Key':'nh3eoUo***Tks9--JIfIt1Gm'},
url: "https://api.parse.com/1/classes/_User/?where={%22$relatedTo%22:\n\
   {%22object%22:}",

success: function(data) {
    //  console.log(data );
      res=data;


    },
    error: function(data) {

      console.log("ko" );
    }


  });

      console.log(res); 
  return res;     





}


});



 return Friendscollection;



 });

如果调用 fetch,则返回空集合:

 Friends.utenti = new Friendscollection();
 Friends.utenti.fetch({async:false});
4

1 回答 1

2

The Backbone.Collection.fetch method is not supposed to return the data but a deferred or promise object. The correct way of doing what you want is like this:

var Friendscollection = Backbone.Collection.extend({
    model: Person,
    url: "https://api.parse.com/1/classes/_User/",
    idAttribute: "objectId",
    parse: function(data) {

        return data.results;
    },

    fetch: function(options) {
        var cur_user = Parse.User.current().id;
        return Backbone.Collection.prototype.fetch.call(this, {
            type: 'GET',
            headers: {
                'X-Parse-Application-Id': 'qS0KLM--h***PiTS3VMk',
                'X-Parse-REST-API-Key': 'nh3eoUo***Tks9--JIfIt1Gm'
            },
            url: this.url + "?where=..."
        });
    }
});

With that you can get the ajax result like this:

var friendscollection = new FriendsCollection();
var res;

friendscollection.fetch().done(function(data) {
    res = data;
}).fail(function(xhr, textStatus, error) {
    console.log(textStatus);
});

That code is asynchronous so you shouldn't expect res to be defined in that same block. That's what the callback for done() is for. To learn more about how deferred objects work take a look at Deferred object

于 2013-08-18T16:13:12.870 回答