注册MouseMove:事件对象始终未定义

Registering for MouseMove: Event object is always undefined

本文关键字:未定义 对象 事件 MouseMove 注册      更新时间:2023-09-26

我有一个注册鼠标移动事件的Javascript对象。但我的问题是,事件参数没有在我的自定义函数中传递,它总是未定义的。

如果你查看下面的函数touchMove(),你会发现参数事件总是由于某种原因而未定义的

我做错了什么?

MyObject.prototype.registerPointerEvents = function()  
{
  var instance = this;  // function() { instance.func(); }
  var ele      = this.getAttrib("divEle");
  ele.addEventListener("mousemove", function() { instance.touchMove(); }, false); 
}
MyObject.prototype.touchMove = function( /*Event*/ event )
{
  // Virtual function to be overridden in child classes
  console.log("MOVE 1: "+event); // here it outputs event is undefined
  if (!event)
     event = window.event;
  console.log("MOVE 2: "+event); // here event is still undefined
  if (this.getAttrib("isDragging") == "true")
  {
     console.log("MOVE TRUE");
     this.getAttrib("divEle").style.left = event.clientX+"px";
     this.getAttrib("divEle").style.top  = event.clientY+"px";
  }
}

当然是未定义的,您正在调用一个没有参数的匿名函数。

更好地使用这个:

ele.addEventListener("mousemove", instance.touchMove, false);

这(几乎)与相同

ele.addEventListener("mousemove", function(e) { instance.touchMove(e); }, false);