Accessing vaadin-grid data inside event listener

Hi:

How can I access the table data on a vaadin-grid inside a custom Polymer element’s event listener? Let’s say I have the following custom element:

<dom-module id="myelement">
  <template>
    <vaadin-grid id="table">
    </vaadin-grid>
  </template>

  <script>
    Polymer ({
        is: 'myelement',

        properties: {
          info: Array,
       },

        ready: function() {
          this.$.table.items = this.info;
          this.$.table.addEventListener
          ( 'selected-items-changed', function ( event ) {
[...]

I cannot access this.info from inside the addEventListener anonymous function, and ‘this’ is just the HTMLElement…how do I get the grid data from the element?

Mona

Hi,

The event target is the vaadin-grid element, so you can access the “items” property from it:

this.$.table.addEventListener( 'selected-items-changed', function ( event ) {
   event.target.items;
});

Hope this helps!

Hi, Mona.

The value of this should be the reference to the element with the event listener added, that is the vaadin-grid element in your case. This is why you can not get this.info in your listener.

To make the value of this be the reference to your element, you should bind your event listener method to your element. For example:

this.$.table.addEventListener( 'selected-items-changed', function( event ) {
  event.target.items;
}.bind(this) );

You can still access the grid element inside a bound listener using the event.target reference.

Note that Polymer provides syntax sugar to simplify using bound event listeners in custom elements, such as the listeners object map and listen/unlisten methods. See the
Polymer Events Guide
.