简体   繁体   中英

polymer v 1.0 .. pass values in annotated event handlers

I was wondering how can I pass values to an event handler , when annotating them to an element in a template.

this works:

 <button on-click="handleClick">

but this doesn't

<button on-click on-click="handleClick(someValue)">

is there a way?

It's not totally clear what you are trying to accomplish. So you might want to clarify it a bit. But taking a guess, it sounds like I might still be able to help you...

Look at this Stack Overflow question , the accepted answer and my comment.

Amit points out you could use HTML5 custom ( data- ) attributes. Like this:

<paper-button id="foo" on-tap="bar" data-args="foo,some other value,2">Click</paper-button>
...
<script>
(function() {
  Polymer({
    is: 'example',
    properties: {...},
    bar: function(e){
      var args = e.target.getAttribute('data-args').split(',');
      // now args = ['foo', 'some other value', '2']
    }
  });
})();
</script>

Which worked for me. However, in my particular use case, I had to use: Polymer.dom(e).path[2].getAttribute('data-args') .

To learn more, you can read this reference on Event Retargeting .

If the handler is scoped inside of the host element you can add a custom property to the element and supply an argument in the attribute that binds to that property. You will only be able to supply one argument to the property, you can use an object. However it is possible to handle the Annotated Events outside of the host element structure and this will mean something else. Using the event that was passed in works always. With a reference to the element itself you will also be able to access these properties and bindings as well as the attributes.

<dom-module id="awesome-element">
    <template>
        <h1>Awesome Element</h1>
        <content></content>
    </template>
    <script>
        polymer({
            is:'awesome-element',
            properties{
                onearg: {
                    type: String,
                    value: ''
                },
                handleClick: function(e){
                    console.log(this.onearg);

                }
            }
        });
    </script>
<dom-module>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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