How to use keyword this in a mouse wrapper in right context in Javascript?

Posted by MartyIX on Stack Overflow See other posts from Stack Overflow or by MartyIX
Published on 2010-04-22T13:23:54Z Indexed on 2010/04/22 13:33 UTC
Read the original article Hit count: 289

Filed under:
|
|
|

Hi,

I'm trying to write a simple wrapper for mouse behaviour. This is my current code:

function MouseWrapper() {

  this.mouseDown = 0;  
  this.OnMouseDownEvent = null;
  this.OnMouseUpEvent = null;
  document.body.onmousedown = this.OnMouseDown;  
  document.body.onmouseup = this.OnMouseUp;
}

MouseWrapper.prototype.Subscribe = function (eventName, fn) {

  // Subscribe a function to the event
  if (eventName == 'MouseDown') {
    this.OnMouseDownEvent = fn;
  } else if (eventName == 'MouseUp') {
    this.OnMouseUpEvent = fn;
  } else {    
    alert('Subscribe: Unknown event.'); 
  }  
}  


MouseWrapper.prototype.OnMouseDown = function () {  
  this.mouseDown = 1;  
  // Fire event
  $.dump(this.OnMouseDownEvent);
  if (this.OnMouseDownEvent != null) {
    alert('test');
    this.OnMouseDownEvent();
  }
}

MouseWrapper.prototype.OnMouseUp = function () {

  this.mouseDown = 0;
  // Fire event
  if (this.OnMouseUpEvent != null) {
    this.OnMouseUpEvent();
  }  
}

From what I gathered it seems that in MouseWrapper.prototype.OnMouseUp and MouseWrapper.prototype.OnMouseDown the keyword "this" doesn't mean current instance of MouseWrapper but something else. And it makes sense that it doesn't point to my instance but how to solve the problem?

I want to solve the problem properly I don't want to use something dirty.

My thinking: * use a singleton pattern (mouse is only one after all) * pass somehow my instance to OnMouseDown/Up - how?

Thank you for help!

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about this