如何在Polymer中加载(然后通过Observer)运行函数

时间:2018-02-26 16:20:10

标签: polymer debouncing debounce

我尝试在加载此Web组件时运行getResponse,然后每次更改过程属性。

但是,在尝试运行此debounce函数时,会调用4次,getResponse会在延迟后运行,但会运行4次而不是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;
  }

}

我该如何实现这种行为?

P.S。还在ready函数中尝试了这种去抖动方法,并且它仍在调用getResponse 4次...(https://codepen.io/tony19/pen/vxZVwx

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

0 个答案:

没有答案