views:

30

answers:

2

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?

+2  A: 

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.

Nick Craver
Thanks, $.proxy() seems that might work, I'll try it out.
Dev er dev
+2  A: 

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) {} ... }

mark
Yes, I hoped for something prettier, but still, this also works.
Dev er dev