【问题标题】:javascript: Accessing parent object from event listener in draw method of jcanvasjavascript:在jcanvas的draw方法中从事件监听器访问父对象
【发布时间】:2013-06-08 23:01:33
【问题描述】:

我正在使用 jcanvas (http://calebevans.me/projects/jcanvas/) 来学习 JavaScript 项目。我有以下代码:

var Board = function($element){
    this.place_piece = function(piece){
         this.board[piece.position[0]][piece.position[1]] = piece;
         $element.drawImage({
              source: piece.image,
              draggable: true,
              layer: true,
              x: this.get_coordinates_by_cell(piece.position)[0],
              y: this.get_coordinates_by_cell(piece.position)[1],
              dragstop: function(layer){
                console.log($this)
                console.log(layer)
              }
          });
}

我需要在 dragstop 函数中访问父 Board 对象的方法。但是当我在那里调用 $this 变量时,我得到的是画布......而不是板本身。有什么可做的吗?

【问题讨论】:

    标签: javascript jquery jcanvas


    【解决方案1】:

    在进入您的 Board 构造函数时,将其分配给一个局部变量(self),以便在同一范围内定义的其他函数可以访问它。

    以下内容将起作用:

    var Board = function($element){
        var self = this;
        this.place_piece = function(piece){
             this.board[piece.position[0]][piece.position[1]] = piece;
             $element.drawImage({
                  source: piece.image,
                  draggable: true,
                  layer: true,
                  x: this.get_coordinates_by_cell(piece.position)[0],
                  y: this.get_coordinates_by_cell(piece.position)[1],
                  dragstop: function(layer){
                    console.log(self)
                    console.log($this)
                    console.log(layer)
                  }
              });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-26
      • 1970-01-01
      • 2010-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多