Marko
Marko

Reputation: 31385

jQuery: how to get original value of this in methods

I'm trying to have some object oriented design using JS and jQuery. I have the following construstor:

function A () {
  this.url = "some url";

   $("rrr").autocomplete({
    source: function(req, add){
       $.getJSON(this.url, req, function(data) {} ...
}

As you guessed, I can't use this.url, since jQuery redefienes this. I can't use just url without this, since it is not declared. What I came up is to have something like this:

function A () {
  this.url = "some url";
  var url = this.url;

   $("rrr").autocomplete({
    source: function(req, add){
       $.getJSON(url, req, function(data) {} ...
}

But this is just plain ugly, and works only for properties.

Is there a better way to fetch value of this from original scope in jquery methods?

Upvotes: 0

Views: 325

Answers (2)

mark
mark

Reputation: 36

The issue is with the 'this' reference being a reference to the object that triggered the event. Keeping a reference to 'this' in your class when it is instanciated is not ideal but will get around this problem (you could call it anything you want but usually 'self' or '_this' is what I call it).

function A () {
  var _this = this;
  _this.url = "some url";


   $("rrr").autocomplete({
    source: function(req, add){
       $.getJSON(_this.url, req, function(data) {} ...
}

Upvotes: 2

Nick Craver
Nick Craver

Reputation: 630409

You can use $.proxy() to set this in the context of the function, like this:

function A () {
  this.url = "some url";
  $("rrr").autocomplete({
     source: $.proxy(function(req, add){
               $.getJSON(this.url, req, function(data) {});
             }, this)
  });
}

Or you can do it long hand by returning a function with the context set, but since you didn't like your current work-around, I'm guessing $.proxy() is much more appealing in your case, and not really much overhead at all here.

Upvotes: 2

Related Questions