Ali
Ali

Reputation: 267287

Jquery events and objects?

I'm trying to do this:

var foo = new Foo();
foo.setEvents( foo );

Code of foo:

function Foo()
{
   this.id = getId(); //this works successfully, each instance of foo gets
                          //assigned a new auto incrementing id e.g 1, 2, 3, etc

   this.setEvents = function( that ) 
   {
      $("#myButton").click( that.bar );
   }

   this.bar = function()
   {
      alert(this.id);
   }
}

Whenever I run this code and click on my button, I get an alert saying 'undefined'

How can I preserve the state of the object whose method I want to run when the event is triggered?

Upvotes: 0

Views: 86

Answers (2)

alex
alex

Reputation: 490607

When that function is called, this points to the native DOM element that handled the event.

You need a reference to the object itself that can be resolved in the scope of that function.

A common method of doing this is with var that = this.

jsFiddle.

Upvotes: 1

Trey
Trey

Reputation: 5520

this refers to something different in jQuerys scope...

function Foo()
{
   obj=this;
   this.id = 1; //this works successfully, each instance of foo gets
                          //assigned a new auto incrementing id e.g 1, 2, 3, etc

   this.setEvents = function( that ) 
   {
      $("#myButton").click( that.bar );
   }

   this.bar = function()
   {
      console.log(obj)
   }
}
var foo = new Foo();
foo.setEvents( foo );

Upvotes: 1

Related Questions