在javascript中使用dojo用事件处理程序示例化变量,“this”是什么?

bvuwiixz  于 2022-12-16  发布在  Dojo
关注(0)|答案(1)|浏览(145)

我在一个对象中创建一个“示例”变量时遇到了麻烦,或者当一个对象的函数作为事件处理程序被调用时,我在一个对象中引用一个“示例”变量时遇到了麻烦。下面是我正在使用的代码。如果这很重要的话,它(显然)使用了dojo。我遇到的问题是针对我的情况吗?针对dojo吗?还是我以一种完全不正确的方式处理这个问题?

dojo.declare("DynDraw", esri.toolbars.Draw, {
  constructor: function () {
    this.myLocalMap = arguments[0];
  }
  , myLocalMap: null
  , subscribed: false
  , activate: function (geometryType, options) {
    this.inherited(arguments);
    dojo.connect(this.myLocalMap, "onMouseDown", this.DynDraw_Map_OnMouseDown);
  }
  , DynDraw_Map_OnMouseDown: function (event) {
    //when called as an event handler (assigned above) “this.subscribed” is undefined
    //”this” seems to be “myLocalMap”, not the “DynDraw” object
    //when called as a “function” “this.subscribed” has a 
    if (this.subscribed == false) {
      dojo.connect(this.myLocalMap, "onMouseMove", this.DynDraw_Map_OnMouseMove);
      this.subscribed = true;
    }
  }
  , DynDraw_Map_OnMouseMove: function (event) {
      console.log("DynDraw_Map_OnMouseMove");
  }
});
odopli94

odopli941#

您需要使用dojo.hitch。这将为函数绑定一个作用域。

dojo.connect(this.myLocalMap, "onMouseDown", 
    dojo.hitch(this, this.DynDraw_Map_OnMouseDown));

http://dojotoolkit.org/reference-guide/1.7/dojo/hitch.html

相关问题