romerk
romerk

Reputation: 238

Polymer - Pass dom-repeated item inside on-click function

How do I pass a dom-repeated item inside a function in on-click? My code doesn't work:

<dom-module id="my-element">

 <template>

   <template is="dom-repeat" items="{{stuff}}>

    <paper-button on-click="_myFunction(item.name)">{{item.name}}</paper-button>

   </template>

 </template>

</dom-module>

<script>
  Polymer({

    is: 'my-element',

    ready: function() {
      this.stuff = [
        { id: 0, name: 'Red' },
        { id: 1, name: 'Blue' },
        { id: 2, name: 'Yellow' },
      ];
    },

    _myFunction: function(color) {
      console.log('You pressed button ' + color);
    },

  })
</script>

Or is there a better approach in achieving something like this? Thanks!

Upvotes: 21

Views: 12313

Answers (2)

pomber
pomber

Reputation: 23980

Short answer
The item is in the event parameter: e.model.item

From the documentation:

When you add a declarative event handler inside the template, the repeater adds a model property to each event sent to the listener. The model is the scope data used to generate the template instance, so the item data is model.item:

<dom-module id="simple-menu">

  <template>
    <template is="dom-repeat" id="menu" items="{{menuItems}}">
        <div>
          <span>{{item.name}}</span>
          <span>{{item.ordered}}</span>
          <button on-click="order">Order</button>
        </div>
    </template>
  </template>

  <script>
    Polymer({
      is: 'simple-menu',
      ready: function() {
        this.menuItems = [
            { name: "Pizza", ordered: 0 },
            { name: "Pasta", ordered: 0 },
            { name: "Toast", ordered: 0 }
        ];
      },
      order: function(e) {
        var model = e.model;
        model.set('item.ordered', model.item.ordered+1);
      }
    });
  </script>

</dom-module>

Note: The model property is not added for event listeners registered imperatively (using addEventListener), or listeners added to one of the template's parent nodes. In these cases, you can use the modelForElement method to retrieve the model data that generated a given element. (There are also corresponding itemForElement and indexForElement methods.)

Upvotes: 7

pikanezi
pikanezi

Reputation: 1128

You can't pass arguments directly to on-click methods, but you can retrieve the item clicked inside a dom-repeat template via the event :

<script>
 Polymer({

 is: 'my-element',

 ready: function() {
   this.stuff = [
     { id: 0, name: 'Red' },
     { id: 1, name: 'Blue' },
     { id: 2, name: 'Yellow' },
   ];
 },

 _myFunction: function(e) {
   console.log('You pressed button ' + e.model.item.name);
 },

});
</script>

See the relevant documentation here.

Upvotes: 45

Related Questions