开发者

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.i开发者_运维百科d);
   }
}

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?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜