如何将参数传递给Polymer事件监听器?

3

如何向注释的事件监听器传递参数?

我有这段代码:

<paper-button id="bt_close" raised on-tap="close">
  Close first movement
</paper-button>

我正在尝试使用一些参数调用我的close函数(例如,on-tap="close(1)"close(2)close(custom_parameter)等)。

我的close函数是:

close: function (p) {
  console.log(p);
}

但是我在控制台中看到了以下错误:
监听器方法close(1)未定义。
1个回答

4

事件注释需要您在Polymer对象定义中提供一个方法名称。在运行时,Polymer通过名称在对象上查找该方法,因此在方法名称中包含参数将导致查找失败,并且您会看到您提到的控制台错误。

要指定参数,您可以使用数据属性,如下所示:

// template
<paper-button on-tap="close" data-foo="1">Close</paper-button>

// script
Polymer({
  _close: function(e) {
    const foo = e.target.dataset.foo;
    // do something with foo
  }
  ...
});

HTMLImports.whenReady(() => {
  Polymer({
    is: 'x-foo',
    _close: function(e) {
      const foo = e.target.dataset.foo;
      console.log('foo', foo);
    }
  });
});
<head>
  <base href="https://cdn.rawgit.com/download/polymer-cdn/1.8.0/lib/">
  <script src="webcomponentsjs/webcomponents-lite.js"></script>
  <link rel="import" href="paper-button/paper-button.html">
</head>
<body>
  <x-foo></x-foo>

  <dom-module id="x-foo">
    <template>
      <paper-button on-tap="_close" data-foo="1">Close</paper-button>
    </template>
  </dom-module>
</body>

{{链接1:codepen}}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接