向事件处理程序函数添加参数

Add Argument to event-handler function?

本文关键字:添加 参数 函数 程序 事件处理      更新时间:2023-09-26

我正在与Polymer合作一个小型web项目。

我正在为项目列表中的每个项目显示一个删除按钮。删除按钮触发deleteItem()-功能。我想添加item.iditem本身作为参数,这样我就可以删除正确的项。

我该怎么做

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

您不能向事件处理程序传递额外的参数,但可以获得对event.model模型的引用。

请参阅https://www.polymer-project.org/1.0/docs/devguide/templates.html#handling-示例的事件

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