简体   繁体   English

向事件处理函数添加参数?

[英]Add Argument to event-handler function?

I'm working with Polymer on a small web-project. 我正在与Polymer一起在一个小型Web项目上工作。

I'm displaying a delete button for every item in a list of items. 我正在为项目列表中的每个项目显示一个删除按钮。 The delete button triggers the deleteItem() -function. 删除按钮触发deleteItem()函数。 I would like to add item.id or item itself as an argument so I can delete the right item. 我想添加item.iditem本身作为参数,以便删除正确的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>

You can't pass additional arguments to the event handler but you can get a reference to the model of the event.model . 您不能将其他参数传递给事件处理程序,但是可以获取对event.model模型的event.model

See https://www.polymer-project.org/1.0/docs/devguide/templates.html#handling-events for an example 有关示例,请参见https://www.polymer-project.org/1.0/docs/devguide/templates.html#handling-events

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM