2

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
  • Incidentally function.bind as in Prototype is a standard part of ECMAScript Fifth Edition so you'll be able to use it anyway in the future without having to hack the function prototype. Commented Feb 13, 2010 at 13:33
  • @bobince: this will be a nice addition, especially because i tend to use .bind alot... Commented Feb 13, 2010 at 13:40
  • Yeah, me too (though through patching Function.prototype myself, as I don't use Prototype). Between this, the Strict Mode fixes, and the addition of long-standard Mozilla features to the language, JavaScript is finally getting a bit less horrible. Commented Feb 13, 2010 at 13:56

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

3 Comments

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?
i've figured it out... seems like the valid syntax for json is '{"ret":"d"}'...
also, there seems to ba an context attribtue to the AJAX request, that does the same trick:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.