views:

28

answers:

3

Hi,

I have a method in a class and into this method i have a handler for a click event in a div element:

function MyClass(container)
{
   this.Container=container;
   this.PrepareHandlers = function()
    {

        $('#Div1').click(function() {
            alert(this.Container);
        });
    }; 
}

But since im into the handler, "this" is the clicked element. Is possible to access to a property of an object from a handler declared inside a method?

Thanks in advance.

Best Regards.

Jose.

+3  A: 
function MyClass(container)
{
   var self = this;
   this.Container=container;
   this.PrepareHandlers = function()
    {

        $('#Div1').click(function() {
            alert(self.Container);
        });
    }; 
}
I.devries
A: 

Correct me if i am wrong. "this" should refer to the function(){..} in click?

jebberwocky
jQuery uses `Function.apply()` ( [read more](http://www.devguru.com/technologies/ecmascript/quickref/apply.html) ) to change the meaning of `this` within the context of the event handler function. In a jQuery event handler, `this` refers the DOM node that triggered the event.
josh3736
A: 

You also might want to try jQuery 1.4's proxy method: http://api.jquery.com/jQuery.proxy/

function MyClass(container)
{
  this.Container=container;
  this.PrepareHandlers = function()
    {
      $('#Div1').click(function() {
        alert(jQuery.proxy(MyClass.Container, MyClass));
      });
    }
}
jonathonmorgan