0

Is there any way to listen for changes to an instance variable in plain Javascript, and then have a method invoke on change?

I would like to update a table with this pattern, starting with this class:

class TableUpdater {
  tabledata;

  async setData(editedRow) {
    const response = await fetch('http://example.com/api', {
      method : 'post'
      , headers : {
        "Content-Type" : "application/json"
      }
      , body : JSON.stringify(editedRow)
    });

    const updatedData = await response.json();
    this.tabledata = updatedData;
  }

  async updateTable(arg1) {
    // can do the below, but it would be nice to decouple setData() from updateTable() 
    // await this.setData(arg1);

    // table creation logic
  }
}

const tableUpdater = new TableUpdater();
Sean D
  • 2,172
  • 4
  • 23
  • 54
  • 1
    Look into the observer pattern. Posting answer as well. – Ayush Gupta Oct 19 '19 at 08:45
  • A simple net lookup (using your own title) would have given you a lot of answers...which is expected prior to post a question (to do a proper research). – Ason Oct 19 '19 at 08:49

1 Answers1

0

class TableUpdater {
  tabledata;
  listeners = [];

  onSetData(listener) {
    this.listeners.push(listener)
  }
  async setData(editedRow) {
    setTimeout((newData) => {
      for (let i = 0; i < this.listeners.length; i++) {
        this.listeners[i](newData)
      }
      this.tableData = newData
    }, 1000, [{
      foo: 'bar'

    }])
  }
}

const tableUpdater = new TableUpdater();
tableUpdater.onSetData(console.log)
tableUpdater.setData();
Ayush Gupta
  • 6,976
  • 5
  • 43
  • 78
  • 1
    code-only answers may solve a problem, yet they're almost 100% of the time **just bad answers**. – connexo Oct 19 '19 at 09:51