0

I have two type of objects "Tobjects" and a more specific "ToDos"

In the parent class controller, I set up a handler to change the model when an event listener fire in the view. The following code works as expected :

export class TObjectController {
    constructor(model,view){
        this.model = model;
        this.view = view;

        this.init()
    }

    //Init
    init(){
        this.view.bindChangeText(this.handleChangeText);
    }

    //Handler   
    handleChangeText = txt =>{      
        this.model.text = txt;      
    }
export class TObjectView {
    constructor(){      
        this.div = document.createElement("div")                
        this.div.classList.add("tobject")           
        this.div.draggable = true

        this.tObjectString = document.createElement("div")  
        this.tObjectString.contentEditable = true;      
        this.tObjectString.classList.add("tobjectString");
                
        this.div.appendChild(this.tObjectString)
    }

    bindChangeText(handler) {this.tObjectString.addEventListener("input",e =>{ handler(e.target.innerText)})}
}

When I do virtually the same things on the subclass it doesn't work and return a "handler is not a function"

export class TodoController extends TObjectController {
    constructor(model,view) {
        super(model,view);                     
    }

    init(){
        super.init()                
        
        this.view.setDone(this.modelDone)
        this.view.bindToggleDone(this.handleToggleDone)
    }

    //Handler
    handleToggleDone = () =>{       
        this.model = false          
    }
}
export class TodoView extends TObjectView {
constructor(){
super();
this.div.classList.add("todo")

        this.done = document.createElement("input")
        this.done.type ="checkbox"  
        this.done.classList.add("todoDone")
    }
    
    bindToggleDone(fonc) {          
        this.done.addEventListener("change",e =>{ fonc(e)})     
    };  

}

If I try to change the arrow function with a "simple" function


handleToggleDone(){     
this.model = false          
}

It returns "cannot set properties of undefined". One problem solved ! It's a function but ... it doesn't have access to "this.model" anymore.
If called directly in the controller, it does though. Only when called from the eventlistener, the access is "broken".

I don't understand why it would work on the parent class and not in the sub class ?

  • 1
    Don't call `init()` from the constructor. The `handleToggleDone = …` field of the child class is not yet initialised by that time. Either get rid of `init` and do all your setup work in the constructor, or remove the `this.init()` call and instead invoke the method *after* creating the (child class) instance. – Bergi Oct 30 '22 at 23:54

0 Answers0