如何从fetch返回ajax结果

时间:2013-08-17 18:35:13

标签: javascript backbone.js

' ave修改了我的集合重写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});

1 个答案:

答案 0 :(得分:2)

Backbone.Collection.fetch方法不应该返回数据,而是返回延迟或promise对象。做你想做的事的正确方法是这样的:

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=..."
        });
    }
});

有了这个,你可以得到这样的ajax结果:

var friendscollection = new FriendsCollection();
var res;

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

该代码是异步的,因此您不应期望在同一个块中定义res。这就是done()的回调。要详细了解延迟对象的工作原理,请查看Deferred object