Flying Emu
Flying Emu

Reputation: 430

Polymer: Capture events of child elements from parent

I was wondering how I can capture events which occur from a child element from the parent as shown below. I know this method works to capture events using this but I need it from the child element.

I don't want to capture the event from the li and transfer information to foo through global variables or other such means because I'll ultimately be implementing a mousemove event which sends the position of the mouse per trigger, and it would be extremely inefficient sending this through the global variables technique (like as demonstrated in the API here) and slow down the app.

<polymer-element name="foo">
  <template>
    <ul>
      <li>This is my child element</li>
    </ul>
  </template>
  <script>
    Polymer('foo', {
      ready: function() {
        document.querySelector('li').addEventListener('mousedown', function() {
            console.log('mousedown event working');
        })
      }
    });
  </script>
</polymer-element>

Thanks in advance for any insight you may provide.

Upvotes: 2

Views: 2591

Answers (1)

Dirk Grappendorf
Dirk Grappendorf

Reputation: 3422

Don't use document.querySelector() because your li element is inside the shadow dom of the Polymer element. Btw. the element name is incorrect, it must contain a dash.

You can use the automatic node finding feature of Polymer to get the li element. Assign an id to the element and use the this.$ property (alternatively if you don't want to assign an id, you can use this.shadowRoot.querySelector()):

<li id="item">This is my child element</li>

this.$.item.addEventListener(...);

But with Polymer you can declaratively assign the callback function to the li element, which results in a much more readable code:

<polymer-element name="my-foo">
    <template>
        <ul>
            <li on-mousedown="{{mousedown}}">This is my child element</li>
        </ul>
    </template>
    <script>
        Polymer('my-foo', {
            mousedown: function() {
                    console.log('mousedown event working');
            }
        });
    </script>
</polymer-element>

Upvotes: 5

Related Questions