mohanaravind
mohanaravind

Reputation: 133

Listening to a polymer attached event from outside that element

In my team we are trying to write some unit tests for polymer custom elements. Most of our custom elements uses Polymer's template binding feature so we have lots of code written under attached callback of a custom element. When writing unit tests for these elements I can only listen to polymer-ready event but what we need is to run our test suite only after the polymer-attached event so the binding has already been complete.

Right now we have done a dirty checking for the element we want to check so that our test suite only runs after the complete template gets bounded.

I have already seen a post where Polymer exposes a way to listen to ready event but what we need is a way to listen to polymer's attached event from outside polymer.

Upvotes: 2

Views: 3990

Answers (2)

Clay Risser
Clay Risser

Reputation: 3578

Wherever you're listening from:

window.addEventListener('custom-element-attached', function() {
  console.log('Custom element attached event has fired');
}.bind(this));

Element you're trying to listen to:

attached: function() {
  var event = new Event('custom-element-attached');
  window.dispatchEvent(event);
}

I havn't tested this code, but it should work.

Upvotes: 4

robdodson
robdodson

Reputation: 6786

I think there are a few ways to solve this.

  1. Fire your own custom event from the new domReady callback or monkey patch domReady in your test harness so it calls any callback the element has already defined, and also dispatches a custom event.
  2. Create a Mutation Observer which monitors the parent element and can detect when a new child has been inserted into the DOM. I've made an example jsbin. Note: The Mutation Observer will not work if your element is already in the DOM. You'll need to setup the Mutation Observer first, then add your element to the page.

Upvotes: 2

Related Questions