我正在尝试创建一个匿名对象,将一个新的canvas元素附加到DOM。这一切都运行正常,但当我尝试在对象内新添加的画布上使用JQuery注册事件时,它不会触发。
我认为这与范围有关,但如何注册这些事件呢?
var game_grid;
$(function() {
game_grid = new GameGrid();
});
(function (window) {
function GameGrid() {
this.initialize();
}
GameGrid.prototype.canvas;
GameGrid.prototype.ctx;
GameGrid.prototype.initialize = function() {
// Append Child to DOM element
this.canvas = document.createElement("canvas");
this.canvas.width = $(".game-grid-container").width();
this.canvas.height = $(".game-grid-container").height();
this.canvas.id = "game_grid";
$(".game-grid-container").html(this.canvas);
// Define Canvas' Context
this.ctx = this.canvas.getContext("2d");
// Set Up Touch Listeners
$(this.canvas).on("vmousedown vmousemove vmouseup", function(e) {
alert("Not Triggering!");
});
}
window.GameGrid = GameGrid;
} (window));
答案 0 :(得分:0)
所以我找到的答案是一起抛弃JQuery并将事件与addEventListener函数绑定。我确信有一种方法可以用JQuery做到这一点,但我可以确认这是有效的。
(function (window) {
function GameGrid() {
this.initialize();
}
GameGrid.prototype.canvas;
GameGrid.prototype.ctx;
GameGrid.prototype.background_color = '#F0F0F0';
GameGrid.prototype.grid_line_color = '#D9D9D9';
GameGrid.prototype.horizontal_division = 8;
GameGrid.prototype.vertical_division = 8;
/* Public Functions */
GameGrid.prototype.initialize = function() {
// Append Child to DOM
this.canvas = document.createElement('canvas');
this.canvas.width = $('.game-grid-container').width();
this.canvas.height = $('.game-grid-container').height();
this.canvas.id = 'game_grid';
$('.game-grid-container').append(this.canvas);
// Define Canvas' Context
this.ctx = this.canvas.getContext('2d');
// Set Up Touch Listeners
document.getElementById('game_grid').addEventListener('mousedown', function(e) {
alert('triggering!');
});
}
window.GameGrid = GameGrid;
} (window));