开发者

Jquery events and objects?

开发者 https://www.devze.com 2023-03-14 21:25 出处:网络
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

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

精彩评论

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

关注公众号