最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Calling up functions from another class in es6 - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 7

The 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);
    }

}
发布评论

评论列表(0)

  1. 暂无评论