3

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?

3 Answers 3

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

        $('#Div1').click(function() {
            alert(self.Container);
        });
    }; 
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

jQuery uses Function.apply() ( read more ) 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.
0

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));
      });
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.