聚合物 - 在点击功能内传递dom重复的项目

rom*_*erk 21 polymer-1.0

如何在点击中传递函数内的dom重复项?我的代码不起作用:

<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>
Run Code Online (Sandbox Code Playgroud)

或者是否有更好的方法来实现这样的目标?谢谢!

pik*_*ezi 45

您不能将参数直接传递给on-click方法,但是您可以通过事件检索在dom-repeat模板中单击的项目:

<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>
Run Code Online (Sandbox Code Playgroud)

请参阅此处的相关文档.


pom*_*ber 7

简答回答
该项目在事件参数中:e.model.item

文档:

在模板中添加声明性事件处理程序时,转发器会将模型属性添加到发送到侦听器的每个事件.模型是用于生成模板实例的范围数据,因此项数据是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>
Run Code Online (Sandbox Code Playgroud)

注意:不会为必须注册的事件侦听器(使用addEventListener)添加模型属性,或者将侦听器添加到模板的其中一个父节点.在这些情况下,您可以使用modelForElement方法检索生成给定元素的模型数据.(还有对应的itemForElement和indexForElement方法.)