Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

polymer-1.0

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!

like image 610
romerk Avatar asked Jul 06 '15 11:07

romerk


2 Answers

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.

like image 152
pikanezi Avatar answered Oct 01 '22 18:10

pikanezi


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.)

like image 40
pomber Avatar answered Oct 01 '22 17:10

pomber