如何用Observer聚合物去抖动

问题描述 投票:0回答:1

我试图在Web组件完成加载时运行getResponse。但是,当我尝试运行它时,debounce函数只是作为异步延迟,并在5000 ms后运行4次。

static get properties() {
  return {
    procedure: {
      type: String,
      observer: 'debounce'
    }
  }
}

debounce() {
  this._debouncer = Polymer.Debouncer.debounce(this._debouncer, Polymer.Async.timeOut.after(5000), () => {
    this.getResponse();
  });
}

getResponse() {
  console.log('get resp');
}

在加载元素时,有什么必要让getResponse运行一次?

polymer polymer-2.x debouncing debounce
1个回答
0
投票

你确定你想要使用debouncer吗?你可以使用connectedCallBack来获得一个时间事件

class DemoElement extends HTMLElement {
  constructor() {
    super();
    this.callStack = 'constructor->';
  }
  
  connectedCallback() {
    this.callStack += 'connectedCallback';
    console.log('rendered');
    fetch(this.fakeAjax()).then((response) => {
      // can't do real ajax request here so we fake it... normally you would do 
      // something like this.innerHTML = response.text();
      // not that "rendered" get console logged before "fetch done"
      this.innerHTML = `
        <p>${this.callStack}</p>
        <p>${response.statusText}</p>
      `;
      console.log('fetch done');
    }).catch(function(err) {
      console.log(err); // Error :(
    });
  }
  
  fakeAjax() {
    return window.URL.createObjectURL(new Blob(['empty']));
  };
}
customElements.define('demo-element', DemoElement);
<demo-element></demo-element>

如果你真的需要使用观察者,你也可以在你的this.isLoaded中设置一个标志connectedCallback()并在你的观察者代码中检查它。

© www.soinside.com 2019 - 2024. All rights reserved.