Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymer 1.0: How to pass an argument to a Polymer function from an attribute?

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> 

Background Research

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.

Previous Attempts

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.

like image 200
Let Me Tink About It Avatar asked Jul 15 '15 21:07

Let Me Tink About It


2 Answers

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> 
like image 90
Amit Avatar answered Oct 08 '22 06:10

Amit


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')); } 
like image 27
Vaibhav Arora Avatar answered Oct 08 '22 04:10

Vaibhav Arora