1

Under the following code, how do I call the function searchBlock() in the canvas click event?this.searchBlock() can't work here!

Board.prototype = {
    addHandlerToBlock:function(){
        this.canvas.onclick = function(e){
            var e = window.event || e;
            var rect = this.getBoundingClientRect();
            var mouseX = e.clientX - rect.left;
            var mouseY = e.clientY - rect.top;
            var clickBlockId = this.searchBlock(mouseX, mouseY) || -1;
            if(clickBlockId >= 0){
                if(canMove(this.puzzle[clickBlockId])){
                    alert("ha")
                }
            }           
            this.refresh(p);
        }
    },
    searchBlock:function(x, y){
        for(var i = 0; i < this.puzzle.length; i++){
            if( x - this.puzzle[i].x > 0 && y - this.puzzle[i].y > 0){
                return i;
            }               
        }

    }
}
3
  • 1
    Like this: var board = new Board(); var block = board.searchBlock(x, y); Commented Oct 29, 2014 at 16:20
  • Is it good to new a board in the prototype function of Board? Commented Oct 29, 2014 at 16:27
  • Ah, no it isn't. I thought you meant an external click canvas onclick handler, my mistake. Let me post a more thorough answer. (It isn't necessarily always bad, but I think you are right to want to avoid it.) Commented Oct 29, 2014 at 16:29

1 Answer 1

2

Try this. It may not be strictly necessary to alias the this variable, but I like to do it because it is possible to invoke the method while passing in a different value for this.

Board.prototype = {
    addHandlerToBlock:function(){
        var that = this;  // alias to "this"
        this.canvas.onclick = function(e){
            ...
            var block = that.searchBlock(x, y);
        }
    },
    searchBlock:function(x, y){
        ...
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.