0

I am trying to run getResponse once when a web components finishes loading. However, when I try to run this, the debounce function just acts as an async delay and runs 4 times after 5000 ms.

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');
}

What is necessary to get getResponse to run once upon the loading of the element?

Matthew
  • 1,461
  • 3
  • 23
  • 49
  • Possible duplicate of [How to Run Function Once On Load (then by Observer) in Polymer](https://stackoverflow.com/questions/48992723/how-to-run-function-once-on-load-then-by-observer-in-polymer) – Jordan Running Feb 27 '18 at 22:36

1 Answers1

0

Are you sure you want to use a debouncer for that? you could just use the connectedCallBack to get a one Time Event

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>

If you really need to use an observer you could also set a flag this.isLoaded in your connectedCallback() and check for that in your observer code.

daKmoR
  • 1,774
  • 12
  • 24
  • Using this method, an AJAX call was run before the `` component loaded, throwing an error. – Matthew Feb 28 '18 at 20:13
  • that seems strange? how are you creating the iron-ajax? maybe try using just fetch... on timing issues it is usually easier to handle than bringing a webcomponent into the mix... – daKmoR Feb 28 '18 at 20:46
  • Could you elaborate on that? I'm not familiar with `fetch`. – Matthew Mar 01 '18 at 21:16
  • I'm not seeing the advantage over a working debounce function. This solution seems a bit convoluted.. – Matthew Mar 02 '18 at 12:52