RubenDFC
RubenDFC

Reputation: 45

How to pass parameter to Polymer event listener?

How can I pass parameters to an annotated event listener?

I have this code:

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

And I´m trying to call my close function with some argument (i.e., on-tap="close(1)" or close(2) or close(custom_parameter), and so on).

My close function is:

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

But I´m seeing this error in the console:

listener method close(1) not defined

Upvotes: 3

Views: 1167

Answers (1)

tony19
tony19

Reputation: 138436

The event annotation requires the name of a method in your Polymer object definition. At runtime, Polymer looks up the method by name verbatim on the object, so including parameters in the method name would cause the lookup to fail, and you'd see the console error you've mentioned.

To specify an argument, you could use use a data attribute like this:

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

codepen

Upvotes: 4

Related Questions