在跨两个文件工作时,无法设置未定义的属性'onclick'

时间:2017-11-08 15:21:16

标签: javascript html typescript canvas

在文件Grid.ts中,我有以下功能:

    get canvas(): HTMLCanvasElement {
        return this._canvas;
    }

    public revive( cell: Cell ) {
        this.cells.push(cell);
    }

    public kill( cell: Cell ) {
        this._cells.splice(this._cells.indexOf(cell));
    }

    public isAlive( cell: Cell ) {
        return this._cells.filter(c => c.asKey() == cell.asKey()).length > 0;
    }

我希望能够在画布上单击并终止/恢复我的网格的某些块以填充或填充。所以在我的main.ts文件中我添加了:

grid.canvas.onclick = (function(e) {

//mouseclick position
let mx = e.offsetX;
let my = e.offsetY;

//calculate grid square numbers rounded to the nearest 10
let gx = Math.round(mx / CELL_SIZE) *10;
let gy = Math.round(my / CELL_SIZE) *10;

//if pressed before, kill it
if(grid.isAlive(Cell.of(gx, gy))) {
    grid.kill(Cell.of(gx, gy));

//else revive or bring to life
} else {
    grid.revive(Cell.of(gx, gy));
}

});

运行时,在尝试点击屏幕之前,我得到:

    Uncaught TypeError: Cannot set property 'onclick' of undefined

就在我打电话grid.canvas.onclick = (function() {...

的行上

为什么grid.canvas未定义,我该怎么做才能解决这个问题?

0 个答案:

没有答案