0

I have the following class declarations:

class DevicesModel{
    constructor(){
        //khoi tao devices 
        this.devices = [];
        this.tt = 1;
    }
    addNewDevice(ma,ten,dvt,trongLuong){
        const device = {tt: this.tt,ma,ten,dvt,trongLuong};
        this.tt += 1;
        this.devices.push(device);
        return device;
    }
}
class DevicesController{
    constructor(){
        this.devicesModel = new DevicesModel();
        this.devicesView = new DevicesView();
    }
    addNewDevice(){
        const maSo = document.getElementById("ma-sp").value;
        const ten = document.getElementById("ten-sp").value;
        const dvt = document.getElementById("dvt").value;
        const trongLuong = document.getElementById("trong-luong").value;
        if (maSo === '' || ten === '' || dvt === '' || trongLuong === '') {
            return;
        }
        //error is here
        this.devicesModel.addNewDevice(maSo,ten,dvt,trongLuong);
        this.devicesView.addNewDevice(maSo,ten,dvt,trongLuong);
        this.tt += 1;
        //dong modal 
        document.querySelector('.bg-modal').style.display = "none";
    }
    start(){
        this.devicesView.showHideModal();
        document.getElementById("save").addEventListener('click',this.addNewDevice);
    }
}
const devicesController = new DevicesController();
devicesController.start();

When I try to add new device the this.devicesModel returns that error. I don't know what is the error in my code.

I would really appreciate any help. Thank you!

user545871
  • 425
  • 2
  • 10
  • 2
    `this` when the click will happen will be the element on which you clicked, so `devicesModel` will be undefined. You need to bind this event-handler to your instance (`.addEventListener('click',this.addNewDevice.bind(this))` or to use an arrow function wrapper `.addEventListener('click', evt => this.addNewDevice())` There are many dupes for that, let me find it. – Kaiido Jun 12 '19 at 07:53
  • I tested your code in jsfiddle, your constructors never seem to run. – Sasha Jun 12 '19 at 07:54

0 Answers0