0

I have this simple constructor where I have a count variable in a state and a button that sums up the count by one when clicked. Here is the code:

import onChange from 'on-change';
import './style.css';

class App {
    constructor() {
        const state = {
            count: 0,
        }
        this.state = onChange(state, this.update);

        this.el = document.createElement('div');
        //if the button is clicked, count sums up by one
        this.btn = document.createElement('button');
        this.btn.textContent = "Click Me!";
        this.btn.addEventListener("click", e => {
            this.state.count = this.state.count += 1;
        })
        this.el.appendChild(this.btn);
        this.el.className = 'container';
    }

    update(path, current, previous) {
        console.log(this.el); // prints undefined
    }
}

const app = new App();
app.update(); //prints the div
document.body.appendChild(app.el);

However the problem is that when the state is updated, I try to console log 'this.el' which is a dom element, returns simply undefined. But when I call the update function directly, then it successfully prints the value. I do not know what I'm missing. Why is my (this.el) returns undefined in the update function which fires everytime that there is a change in state, but works when called directly outside of the constructor? Thank you very much.

n9iels
  • 867
  • 7
  • 21
  • @Andreas Sorry, just fixed it – ullieiseenstupidhond12 Oct 30 '22 at 13:14
  • The issue is that you passed `this.update` to `onChange` and not `this.update.bind(this)` or `(path, current, previous) => this.update(path, current, previous)` or the like. Currently, since the library will call the function simply as `fn()` and not `yourObject.fn()`, there is no `this` set. – CherryDT Oct 30 '22 at 13:18

0 Answers0