【问题标题】:How to Debounce with Observer Polymer如何使用观察者聚合物去抖动
【发布时间】:2018-08-06 10:55:33
【问题描述】:

我正在尝试在 Web 组件完成加载时运行一次 getResponse。但是,当我尝试运行它时,debounce 函数只是充当异步延迟,并在 5000 毫秒后运行 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】:

您确定要为此使用去抖动器吗?您可以只使用 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);
&lt;demo-element&gt;&lt;/demo-element&gt;

如果您确实需要使用观察者,您还可以在您的 connectedCallback() 中设置标志 this.isLoaded 并在您的观察者代码中检查它。

【讨论】:

  • 使用该方法,在&lt;iron-ajax&gt;组件加载之前运行AJAX调用,抛出错误。
  • 这看起来很奇怪?你是如何创建 Iron-ajax 的?也许尝试只使用 fetch... 在时间问题上,它通常比将 web 组件加入到组合中更容易处理...
  • 您能详细说明一下吗?我不熟悉fetch
  • 我没有看到与工作去抖动功能相比的优势。这个解决方案似乎有点令人费解..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-03
  • 2017-02-10
  • 1970-01-01
  • 1970-01-01
  • 2017-02-03
  • 1970-01-01
相关资源
最近更新 更多