Search code examples
javascriptcreatejses6-class

Pass event object to setter method in event callback


I am working with createjs library.

I have the following class:

class Person {
 constructor(){
  this.name = 'John';
 }

 set updateName(event){
  this.name += event.key;
 }
}

Next, I instantiate the object like this:

var human = new Person();

I am trying to update the name of the person upon each keystroke like this:

window.addEventListener.on('keydown', human.updateName);

However, I get an error of "Cannot read property 'handleEvent' of undefined".


Solution

  • human.updateName attempts to read the updateName property. Since you haven't defined a getter for it, the result of that is undefined. Apparently whatever you're passing it to (window.addEventListener.on) expects to be passed something other than undefined.

    To pass the actual setter function is a bit tricky, you have to get access to it via getOwnPropertyDescriptor and then pass it in:

    window.addEventListener.on('keydown', Object.getOwnPropertyDescriptor(human, "updateName").set);
    

    In order to ensure that the right person was updated, you'd probably need bind as well:

    window.addEventListener.on('keydown', Object.getOwnPropertyDescriptor(human, "updateName").set.bind(human));
    

    Alternately, it would be rather simpler just to use an arrow function as glue:

    window.addEventListener.on('keydown', e => {
        human.updateName = e;
    });
    

    Side note: updateName is the kind of name you'd give a method, not a property. Normally, a property would be called simply name.

    Perhaps you intended it to be a method instead? If so:

    class Person {
     constructor(){
      this.name = 'John';
     }
    
     updateName(event){ // No `set` on this line
      this.name += event.key;
     }
    }
    

    ...and

    window.addEventListener.on('keydown', human.updateName.bind(human));
    

    or

    window.addEventListener.on('keydown', e => {
        human.updateName(e);
    });