views:

3172

answers:

4

My page deals with many "Store" objects, each of them has a field called 'data'. However, this data is fetched via AJAX requests which may be parallely going on.

function Store(id){
    this.id = id;
    this.queryparam = 'blah';
    this.items = null;
}

Store.prototype.fetch = function(){
    $.get("/get_items",{q:this.quaryparam},function(data,status){

      // how to store the received data in this particular store object? Being
      // a callback function, I don't have a reference to this object as 'this'

       // this.data = data; //will not work
    });
}

In the callback function I tried defining a default parameter to the calling objects as following:

$.get("/get_items",{q:this.quaryparam},function(data,status, ref = this) ...

But turns out that javascript does not support default argument values like this. Can I somehow get jquery to pass a reference to 'this' store in the callback function?

I thought of a couple of other approaches but none of them work:

I could set the store data using synchronous requests but then thats not the point of AJAX, is it?

Another way for me could be, to send the store id also in the requests which will come back in the response. For eg:

// in Store.fetch()
$.get("/get_items",{q:this.quaryparam,id:this.id},function(responsetext,status){
    var response = eval(responsetext);
    stores[response.id].data = response.data;
});

I do not like this approach because this pollutes the response just because the client-side code was unable to keep track of which request was sent by which object.

Moreover, since store.id is client-specific, it will also mess up caching at the server. A different request URL will be used for two different stores even though they have the same query parameters.

Is there any other way to achieve what I want?

+1  A: 

Hi, I think you can do:

function Store(id){
    this.id = id;
    this.queryparam = 'blah';
    this.items = null;
}

Store.prototype.fetch = function(){
    var that = this;
    $.get("/get_items",{q:this.quaryparam},function(response){
        that.callback(response)
    });
}

Store.prototype.callback = function(response){
    // and here you can use
   this.items = response // just example
}
Ricardo Vega
+4  A: 

You should be able to use closure:

var tmp = this;
$.get("/get_items",{q:this.quaryparam},function(data,status){
    tmp.data = data;
});

Is that what you mean?

Marc Gravell
A: 

Seems to be working, although I don't understand how the variable 'tmp' is accessible inside the anonymous function. :-)

Thanks Marc and ricardoe !

This is what closure does. Google for "closure" and "lexical scope" - these are important concepts to understand in JavaScript.
Rene Saarsoo
A: 

I wrote this plugin, I think it will be useful

http://code.google.com/p/jquerycallback/