开发者

Using jQuery in a class

I've got a scope problem.

I have a class with a mouseX and mouseY property.

I wanted to set them using jQuery, like this:

// Store the mouse position at all times
$('#'+canvasId).mousemove( function(e) {
    this.mou开发者_开发百科seX = e.pageX-this.offsetLeft;
    this.mouseY = e.pageY-this.offsetTop;
});

Works fine, only this.mouseX stays in the function scope. I've implicitly declared mouseX and mouseY in the class using this. If I don't they become private variables, right?


I think you want something more like the following:

// I usually put this at the top of my class declaration
var that = this;

// Store the mouse position at all times
$('#'+canvasId).mousemove( function(e) {
    that.mouseX = e.pageX-this.offsetLeft;
    that.mouseY = e.pageY-this.offsetTop;
});

Since this changes meaning inside an event handler, you need to save a reference to it for later use; the conventional name for such a saved reference is that.


Your could do something along the lines of this:

// Store the mouse position at all times
var base = this;
// ...
$('#'+canvasId).mousemove( function(e) {
    base.mouseX = e.pageX-this.offsetLeft;
    base.mouseY = e.pageY-this.offsetTop;
});

Oh, and yes. If you don't use this for variables within a class definition, you won't be able to access them through an instance.


You could use little know jQuery.proxy() function. Something like this:

var obj = {
  mouseX: 0,
  mouseY:0,
  el:$('#'+canvasId),
  mousemove: function(e) {
    this.mouseX = e.pageX-this.el.offsetLeft;
    this.mouseY = e.pageY-this.el.offsetTop;
  }
};

$('#'+canvasId).mousemove( jQuery.proxy( obj.mousemove, obj ) );

Of course you no longer get access to the original jQuery element via this, so you have to save it as a property of the object, something like this.el, beforehand

You can even create the event within the object like so:

this.el.mousemove( jQuery.proxy( this.mousemove, this ) );


I've implicitly declared mouseX and mouseY in the class using this. If I don't they become private variables, right?

Using this ties those properties to the current function scope (which in your case is the jquery mousemove function). If you remove the this then those variables will become globals. Private properties can be declared using var.

Private Variables:

// Store the mouse position at all times
$('#'+canvasId).mousemove( function(e) {
    var mouseX = e.pageX-this.offsetLeft;
    var mouseY = e.pageY-this.offsetTop;
});

Global Variables:

// Store the mouse position at all times
$('#'+canvasId).mousemove( function(e) {
    mouseX = e.pageX-this.offsetLeft;
    mouseY = e.pageY-this.offsetTop;
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜