views:

38

answers:

1

Hello, i've used prototype before, and i'm trying to learn jquery now. The problem: I have an object that makes an ajax call, and i want the success callback to call a function within my object. The problem is that inside the callback function, "this" does not point to my original class.

Example:

function C(){
    this.loadData();
}
C.prototype.loadData = function(){
    $.ajax({
       url:"URL/",
       dataType:'json',
       success:this.dataRetreived
    });
}
C.prototype.dataRetreived = function(JSON){
    console.info(this);
    console.info(JSON);
}

Using Prototype i'd could simply use .bind(this), but jquery has a different way of doing things..

+3  A: 

There's a "proxy" method in jQuery 1.4 that's kind-of like "bind" in Prototype or Functional:

  success: $.proxy(instanceOfC, C.prototype.dataRetrieved)
Pointy
i'm now testing this variant, seems that the .proxy does the trick... but it seems that my json string returned from the server is invalid....`window.JSON.parse('{ret:"d"}')` seems to be considered invalid in firefox (tried thia in the firebug console and it raises `SyntaxError: JSON.parse { message="JSON.parse", more...}`. Any ideeas why is says that?
Quamis
i've figured it out... seems like the valid syntax for json is `'{"ret":"d"}'`...
Quamis
also, there seems to ba an `context` attribtue to the AJAX request, that does the same trick:)
Quamis
@Quamis thanks, that's extremely nice to know!
Pointy