My problem is very simple. Basically, I have a Controller and a View class. When I click a button, the controller tells the view to display a thing. Problem is, the Controller can't. Here's the code.
class Controller {
constructor(view) {
view = new View();
let button = document.getElementById('button');
button.addEventListener('click', () => {
controller.doThing();
});
}
doThing() {
view.drawThing(5, 5);
}
}
class View {
constructor(controller) {
let canvas = document.getElementById('canvas');
let pen = canvas.getContext('2d');
this.controller = Controller;
this.drawThing = drawThing();
}
drawThing(x, y) {
pen.beginPath();
pen.moveTo(0, 0);
pen.lineTo(x, y);
pen.stroke();
}
}
My problem is very simple. Basically, I have a Controller and a View class. When I click a button, the controller tells the view to display a thing. Problem is, the Controller can't. Here's the code.
class Controller {
constructor(view) {
view = new View();
let button = document.getElementById('button');
button.addEventListener('click', () => {
controller.doThing();
});
}
doThing() {
view.drawThing(5, 5);
}
}
class View {
constructor(controller) {
let canvas = document.getElementById('canvas');
let pen = canvas.getContext('2d');
this.controller = Controller;
this.drawThing = drawThing();
}
drawThing(x, y) {
pen.beginPath();
pen.moveTo(0, 0);
pen.lineTo(x, y);
pen.stroke();
}
}
The result of which is an
Uncaught TypeError: Cannot read property 'drawThing' of undefined
at Controller.doThing (Controller.js:17)
at HTMLButtonElement.Controller.button.addEventListener (Controller.js:12)
Share
Improve this question
asked Dec 18, 2016 at 14:43
a.aneva.anev
1352 gold badges4 silver badges11 bronze badges
1 Answer
Reset to default 7The view
variable is scoped only to the constructor. You should use this.view
instead:
class Controller {
constructor(view) {
this.view = new View();
let button = document.getElementById('button');
button.addEventListener('click', () => {
controller.doThing();
});
}
doThing() {
this.view.drawThing(5, 5);
}
}