39

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.

Let Me Tink About It
  • 15,156
  • 21
  • 98
  • 207
  • An associate says: Always a literal string like in your example? You could do something like `on-tap="bar" data-bar="foo"`, then in your event handler, `e.srcElement.getAttribute('data-bar')`. You can't pass an argument like you tried to do. – Let Me Tink About It Jul 15 '15 at 21:58

8 Answers8

47

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>
Amit
  • 45,440
  • 9
  • 78
  • 110
  • 5
    Actually, I had to use `Polymer.dom(e).path[2].getAttribute('data-args')`. See here: https://www.polymer-project.org/1.0/docs/devguide/events.html#retargeting Answer accepted! – Let Me Tink About It Jul 18 '15 at 09:58
  • 17
    `e.target.dataset.args` has worked for me and looks a little cleaner. – Andrew Sep 09 '15 at 19:36
  • @Andrew - you're right. that's a better an cleaner syntax, and considering that I myself wrote HTML5, it's legitimate to use. But in reality, if *not* using the `dataset` property and doing it the way I did, you get better backward compatibility. – Amit Sep 09 '15 at 19:42
  • 1
    What is the argument is from property, as: data-args="{{some_prop}}", upper solutions are not working. Any idea? (ping @Amit @Mowzer) – Goce Ribeski Nov 20 '15 at 13:31
  • 9
    founded, should be: data-args$="{{some_prop}}" https://www.polymer-project.org/1.0/docs/devguide/data-binding.html#attribute-binding – Goce Ribeski Nov 20 '15 at 13:53
  • I used e.target.dataArgs and worked (maybe a more recent version?) – Mathter May 24 '16 at 08:08
46

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'));
}
Let Me Tink About It
  • 15,156
  • 21
  • 98
  • 207
Vaibhav Arora
  • 462
  • 4
  • 8
  • 4
    Actually this is the correct answer using Polymer 1.7.0 APIs, the previous answer is now obsolete – Raffaeu Oct 25 '16 at 13:54
  • 1
    With the speed this framework is progressing, stack overflow can be misleading at times :). – Vaibhav Arora Nov 05 '16 at 15:48
  • I think that holds true for every framework... For all it counts, I'll be active here, answering as many questions I encounter while developing since I'm working on Polymer for my weekend projects now ... – Vaibhav Arora Nov 05 '16 at 15:49
  • 1
    In `item.task`, what does `task` signify? Couldn't find it in the template mentioned above. – sudheeshix Jan 10 '17 at 14:09
  • 3
    This is actually the correct version for Polymer >= 1.x So, this one should be marked as correct, according to Polymer docs – Raffaeu Feb 02 '17 at 15:11
  • It worked for me... and I think perhaps the best approach. – Ch Faizan Mustansar Aug 16 '17 at 09:37
  • 1
    This looks really linked to the dom-repeat feature only: https://www.polymer-project.org/2.0/docs/devguide/templates#handling-events – GGirard Aug 31 '17 at 13:54
10

Shining more light on a subtle difference mentioned in the comments above.

Notice $= must be used if reading a data binding.

<paper-button on-tap="_handleTap" data-foo="foo" data-bar$="[[bar]]">Tap</paper-button>

...

_handleTap: function(e) {
  var foo = e.target.dataset.foo;
  var bar = e.target.dataset.bar;
}

Inside dom-repeat, the item (or whichever name you give it) is available at e.model.item.

<template is="dom-repeat" items="[[items]]" as="someItem">
  <paper-button on-tap="_handleTap">Tap</paper-button>
</template>

...

_handleTap: function(e) {
  var item = e.model.someItem;
}
Jacob Phillips
  • 8,841
  • 3
  • 51
  • 66
2

Is there a way to pass an argument to a Polymer function from an attribute of an element inside its <template>.

Instead of using an event use a computed binding. Computed bindings can accept literal strings.

Checkout the working example below. In this example a button can be hidden based on the parameter that is passed.

<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>
  <button id="foo-one" on-tap="barEvent">Click foo-one</button>
  <button id="foo-two" hidden="{{barTest('value-two')}}">Click foo-two</button>
  <button id="foo-three" hidden="{{barTest('value-three')}}">Click foo-three</button>
 </template>
</dom-module>
<script>
 Polymer({
  is: "example-element",
  barEvent: function (event) {
   console.log(event.target.id);
  },
  barTest: function (arg) {
   if (arg === "value-two") {
    return true;
   } else {
    return false;
   }
  }
 });
</script>

<example-element></example-element>

Note: You can get the id or other attributes of an element that an event is run on through event.target. If you are only looking for other attributes as parameters this might also be a valid solution.

coderfin
  • 1,708
  • 19
  • 24
1

After trying the solutions suggested here which none of them worked, I did a slight modification of @Amit and @Mowzer solutions I got it working like this:

<dom-module id="dial-buttons">

    <template>
        <div on-click="handleClick" data-args="0, num-input">
            <p>0</p>
            <paper-ripple></paper-ripple>
        </div>
    </template>

    <script>
        Polymer({
            is: 'dial-buttons',
            properties: { ... },
            handleClick: function(e) {
                var args = Polymer.dom(e).path[1].getAttribute('data-args').split(',');
                alert(args[0] + args[1]);
            }
        });
    </script>

</dom-module>
Let Me Tink About It
  • 15,156
  • 21
  • 98
  • 207
Waleed Asender
  • 1,477
  • 15
  • 27
0

Just now I got this to work:

<paper-button id="foo" on-tap="bar" data-args="baz,qux,quux">Click</paper-button>
...
<script>
(function() {
  Polymer({
    is: 'example',
    properties: {...},
    bar: function(e){
      var args = e.target.dataset.args.split(','); // ['baz', 'qux', 'quux']
    }
  });
})();
</script>
Let Me Tink About It
  • 15,156
  • 21
  • 98
  • 207
0

Possibly the most robust way to retrieve the argument is as follows:

<paper-button on-tap="_getArgs"
              data-args="foo,bar,qux">Click</paper-button>
...
_getArgs: function(e) {
  var args = Polymer.dom(e).rootTarget.getAttribute('data-args');
  ...
}
Let Me Tink About It
  • 15,156
  • 21
  • 98
  • 207
0

Depending on the situation, the clean way to do this is usually using dom-repeat. If you can format your data as an array of objects, you can just use e.model to get everything.

mullens
  • 28
  • 4