1

I've tried to design some classes to support a callback functionality. Classes MyClass1 and MyClass2 didn't work. Class3 worked, but the design is really horrible. It uses a external class reference to call the method. I'd like to implement a design similar to MyClass1, which is a lot clearer and isn't coupled to an external variable. This callback mechanism would really be great to ajax calls too. $j is just an alias to jQuery.

function MyClass1() {  
    $j("#myDiv1").click(this.func);

    this.func = function() {
        alert("Inside method.");
    }
}

var _class2;  
function MyClass2() {  
    _class2 = this;  
    $j("#myDiv2").click( _class2.func );

    this.func = function() {
        alert("Inside method.");
    }
}

function MyClass3() {  
    $j("#myDiv3").click( function() { cls3.func(); } );   

    this.func = function() {
        alert("Inside method.");
    }
}

var cls1 = new MyClass1();  
var cls2 = new MyClass2();  
var cls3 = new MyClass3();  
Peter Bailey
  • 105,256
  • 31
  • 182
  • 206
gsb
  • 1,219
  • 1
  • 16
  • 31

1 Answers1

5

Closures are your friend.

function MyClass()
{
  // This local variable can be closed by the anonymous
  // function below
  var self = this;

  $('#myDiv1').click( function()
  {
    self.func();
  });

  this.func = function()
  {
    alert("Inside method.");
  }
}
Peter Bailey
  • 105,256
  • 31
  • 182
  • 206
  • 1
    See also http://stackoverflow.com/questions/2025789/preserving-a-reference-to-this-in-javascript-prototype-functions. It's quite important to understand how `this`-binding actually works in JavaScript (answer: weirdly) when working with observers and delegates. – bobince Apr 06 '10 at 20:22