Jose3d
Jose3d

Reputation: 9277

jquery click handler and Oriented object programming

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?

Upvotes: 3

Views: 754

Answers (3)

jonathanatx
jonathanatx

Reputation: 1613

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

Upvotes: 0

jebberwocky
jebberwocky

Reputation: 1089

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

Upvotes: 0

I.devries
I.devries

Reputation: 8916

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

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

Upvotes: 4

Related Questions