Somehow when executing this code, I get the alert from line 29 .mouseOnSeat. But I don't know why this.seats is null, while in the draw function it is not. I call the init function from html5.
//init called by html5
function init() {
var cinema = new Cinema(8, 10);
cinema.draw("simpleCanvas");
var canvas = document.getElementById("simpleCanvas");
//add event listener and call mouseOnSeat
canvas.addEventListener('mousedown', cinema.mouseOnSeat, false);
}
var Cinema = (function () {
function Cinema(rows, seatsPerRow) {
this.seats = [];
this.rows = rows;
this.seatsPerRow = seatsPerRow;
var seatSize = 20;
var seatSpacing = 3;
var rowSpacing = 5;
var i;
var j;
for (i = 0; i < rows; i++) {
for (j = 0; j < seatsPerRow; j++) {
this.seats[(i * seatsPerRow) + j] = new Seat(i, j, new Rect(j * (seatSize + seatSpacing), i * (seatSize + rowSpacing), seatSize, seatSize));
}
}
}
Cinema.prototype.mouseOnSeat = function (event) {
//somehow this is null
if (this.seats == null) {
alert("seats was null");
return;
}
for (var i = 0; i < this.seats.length; i++) {
var s = this.seats[i];
if (s.mouseOnSeat(event)) {
alert("Mouse on a seat");
}
}
alert("Mouse not on any seat");
};
Cinema.prototype.draw = function (canvasId) {
var canvas = document.getElementById(canvasId);
var context = canvas.getContext('2d');
var i;
//somehow this isn't
for (i = 0; i < this.seats.length; i++) {
var s = this.seats[i];
context.beginPath();
var rect = context.rect(s.rect.x, s.rect.y, s.rect.width, s.rect.height);
context.fillStyle = 'green';
context.fill();
}
};
return Cinema;
})();
I tried a lot, like creating a self variable (var self = this ) and then calling from self.mouseOnSeat, it was suggested on another post, but I didn't figure it out.
Cinemaare not conflicting?selfvariable only works if your function definition is inside the function that has the correctthis. For example if you did not have a separatemouseOnSeatfunction but defined that function inline inside theaddEventListenercall, you could use that trick to replacethiswithselfand there would be no problems.