简体   繁体   中英

1 of the all object methods not working with eventHandler mouse click

All methods in the class above are working fine if a call them.

But when I call them with addEventListener(Click), the object method open() does not work but other methods work here also. Kindly help me find where have I made the error?

class Cell {
    constructor (x,y) {
        this.x = x
        this.y = y
        this.w = cellWidth
        this.h = cellHeight
        this.opened = false
        this.hasMine = true

    }
    squareTest () {
        c.beginPath()
        c.rect(100,100,100,100)
        c.stroke()
    }

    cellBody () {
        c.beginPath()
        c.fillStyle = "rgba(0, 100, 100, 0.1)"
        c.strokeStyle = "rgba(0, 100, 100, 1)"
        c.rect (this.x, this.y, this.w, this.h)
        c.fill()
        c.stroke ()

        if (this.opened === true) {
            if (this.hasMine === true) {
             c.beginPath();
             c.ellipse(this.x + this.w/2, this.y + this.w/2, 10, 10, 15,0,Math.PI*2,false);
             c.stroke()
            }
        }
    }

    open () {
        if(this.opened == false) {this.opened = true}
    }
        }

}

// I have removed some code here to make this post short.

// open() function works fine without addEventListener(Click), // But other methods work well anywhere, so what is different with open()?

// table [0][0] is the object of the Class Cell

table[0][0].open();
// works fine here

table[0][0].squareTest();
// works fine here

canvas.addEventListener ('click', function (event) 
  {
    table[0][0].open(); // DOES NOT WORK HERE

    table[0][0].squareTest(); //works fine here
    console.log (table[1][1]); //works fine
    }
)

table[0][0].open();
    // works fine here

canvas.addEventListener add an anonymous function to be called onclick

You should assign a variable to table[0][0] outside if you want to call it inside that function.

const tb = table[0][0];
canvas.addEventListener('click', function (event) 
   {
     tb.open();
     tb.squareTest();
   }
);

This way you will have a reference to that table to be used inside your onclick function;

This is assuming you have a console error that says table[0][0] is undefined. Is this the case?

There was no error in the code.... But I was not getting the desired output because there was another function which was not called with the open()

Thanks everyone:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM