How to Run Function Once On Load (then by Observer) in Polymer

混江龙づ霸主 提交于 2019-12-11 04:57:41

问题


I am trying to run getResponse once when this web component loads, and then each time the procedure property changes.

However, when trying to run this debounce function, it is invoked 4 times and getResponse runs after a delay, but 4 times instead of 1.

static get properties() {
    return {
      procedure: {
        type: String,
        observer: 'getResponse'
      },
      timeout: {
        type: Number,
        value: null
      }

    }
  }

  ready() {
    super.ready();
    this.debounce();
  }

  debounce() {
    console.log('debounce');
    this.procedure = 'getInventoryActive';
    clearTimeout(this.timeout) // Clear the timeout if it has already been set.
                               // This will prevent the previous task from executing if it has been less than <MILLISECONDS>
    let that = this;           // Make a new timeout set to go off in 800ms
    this.timeout = setTimeout( () => {
      that.getResponse();
    }, 8000);
  }

  getResponse() {
    // do something;
  }

}

How can I achieve this behavior?

P.S. Also tried this debounce method within the ready function, and it's still invoking getResponse 4 times... (https://codepen.io/tony19/pen/vxZVwx)

debounce() {
  this.procedure = 'name';
  this._debouncer = Polymer.Debouncer.debounce(this._debouncer, Polymer.Async.timeOut.after(8000), () => {
    this.getResponse();
  });
}

来源:https://stackoverflow.com/questions/48992723/how-to-run-function-once-on-load-then-by-observer-in-polymer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!