开发者

Use objects method as callback

I've got another JavaScript/jQuery-Problem. A minimal example could be this: I've got a div, and want some JavaScript executed, when the mouse enters. But for some reasons (= in reality, there a many divs, and for each data needs to be kept) I want to use a object as handler for the callback. Here's a small example:

function handler($thediv)
{
   this.somedata = 8;
   
   $thediv.mouseenter(function() { this.callback(); });
}

handler.prototype.callback = function()
{
   alert(somedata);
}

An object is created when the document is loaded:

$(document).ready( function() {
  new handler($("div"));
});

Nothing happens - except that the constructor is executed. I've tried and searched for hours now, but I can't fix this... probably too trivial?

Edit: A complete example.

<html>
 <script type="text/javascript" src="jquery-1.6.js&quo开发者_高级运维t;></script>
 </head>
 <body>

  <div>
   blah blahasdasdadsssssssssssssss
asddddddddddddddddddddddddddd
  </div>
 </body>
 <script type="text/javascript">
   $(document).ready(function() {
     new handler($("div"));
  });

  function handler($thediv)
  {
    this.somedata = 8;

    $thediv.mouseenter(this.callback);
  }

  handler.prototype.callback = function()
  {
    alert(somedata);
  }

  </script>
</html>


The biggest issue here is the use of this in various contexts. Within the mouseenter function, this refers to div, not the object.

This should work:

http://jsfiddle.net/Nx5c7/

function handler($thediv)
{
   this.somedata = 8;
   this.theID=$thediv.attr("id");

   var obj=this;

   $thediv.mouseenter(function() { 
       obj.callback(); 
   });
}

handler.prototype.callback = function()
{
    alert(this.theID + " : " + this.somedata);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜