Is there a way to pass an argument to a Polymer function from an element attribute inside its <template>
?
<script src="http://www.polymer-project.org/1.0/samples/components/webcomponentsjs/webcomponents-lite.js"></script> <link rel="import" href="http://www.polymer-project.org/1.0/samples/components/polymer/polymer.html" /> <dom-module id="example-element"> <template> ... <paper-button id="foo" on-tap="bar">Click</paper-button> ... </template> </dom-module> <script> (function() { Polymer({ is: 'example-element', properties: {...}, bar: function(arg){ // Do stuff using argument arg } }); })(); </script>
I have combed through the documentation which appears silent on the matter. It doesn't say whether you can or can not. But when I try it, it fails. But maybe I'm not doing it correctly. So I need some assistance.
The only thing I have come across is event listeners which doesn't seem to be able to take the arguments I want to pass. Say, an id
or a name
.
I have tried (unsuccessfully) doing things like:
<paper-button id="foo" on-tap="bar('foo')"> Click </paper-button>
but nothing seems to work.
The event listeners idea doesn't work because they limit the arguments and I can't get the, say, id
I need.
You could utilize HTML5 data attributes instead. Try 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>
After searching a lot, I found what I think is the cleanest possible solution.
If the paper-button is inside a template, e.g.
<template is="dom-repeat" items="{{allItems}}" as="item"> <paper-button on-tap="itemTapped">[[item.text]]</paper-button> </template>
Then the properties can be accessed via "model" property in event object passed to function.
itemTapped: function(oEvent){ // oEvent.model.get is the getter for all properties of "item" in your bound array console.log(oEvent.model.get('item.task')); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With