Search code examples
javascriptpolymerweb-component

Add Argument to event-handler function?


I'm working with Polymer on a small web-project.

I'm displaying a delete button for every item in a list of items. The delete button triggers the deleteItem()-function. I would like to add item.id or item itself as an argument so I can delete the right item.

How can I do this?

<template id="bind" is="dom-bind">
  <script>
    var bind = document.querySelector('#bind');
    bind.deleteItem = function() {
      // Get item id?
    }
  </script>

  <template is="dom-repeat" items="{{data}}">
    <span>{{item.name}}</span>
    <paper-button on-click="deleteItem" id="{{item.id}}">Delete</paper-button></p>
  </template>
</template>

Solution

  • You can't pass additional arguments to the event handler but you can get a reference to the model of the event.model.

    See https://www.polymer-project.org/1.0/docs/devguide/templates.html#handling-events for an example

    <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; // <== get the model from the clicked item
            model.set('item.ordered', model.item.ordered+1);
          }
        });
      </script>
    
    </dom-module>