Question

I am using jcanvas (http://calebevans.me/projects/jcanvas/) for my learning javascript project. I have the following code:

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)
              }
          });
}

I need to access methods of the parent Board object inside the dragstop function. But when I call $this variable there, I am getting canvas... not the board itself. Is there anything to do there?

Was it helpful?

Solution

On entering your Board constructor, assign this to a local variable (self) so other functions defined in the same scope can have access to it.

Something like the following will work:

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)
              }
          });
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top