Controlling the value of 'this' in a jQuery event

Solution 1:

You can use jQuery.proxy() with anonymous function, just a little awkward that 'context' is the second parameter.

 $("#button").click($.proxy(function () {
     //use original 'this'
 },this));

Solution 2:

I like your way, in fact use a similar construction:

$('#available_input').bind('click', {self:this}, this.onClick);

and the first line of this.onClick:

var self = event.data.self;

I like this way because then you get both the element clicked (as this) and the "this" object as self without having to use closures.

Solution 3:

jQuery has the jQuery.proxy method (available since 1.4).

Example:

var Foo = {
  name: "foo",

  test: function() {
    alert(this.name)
  }
}

$("#test").click($.proxy(Foo.test, Foo))
// "foo" alerted