Polymer 1.0:如何从属性中将参数传递给Polymer函数?

Mow*_*zer 38 polymer polymer-1.0

有没有办法从其内部的元素属性传递参数到Polymer函数<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>
Run Code Online (Sandbox Code Playgroud)

背景研究

我已经梳理关于此事的沉默文件.它没有说你是否可以.但是当我尝试它时,它失败了.但也许我没有正确地做到这一点.所以我需要一些帮助.

我唯一遇到的是事件监听器,它似乎无法接受我想传递的参数.说,一个id或一个name.

以前的尝试

我尝试过(不成功)做的事情:

<paper-button id="foo" on-tap="bar('foo')"> Click </paper-button>
Run Code Online (Sandbox Code Playgroud)

但似乎没什么用.

事件监听器的想法不起作用,因为它们限制了参数,我无法得到,比方说,id我需要.

Ami*_*mit 46

您可以使用HTML5数据属性.试试这样:

<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>
Run Code Online (Sandbox Code Playgroud)

  • `e.target.dataset.args`对我有用,看起来有点干净. (16认同)
  • 成立,应该是:data-args $ ="{{some_prop}}"https://www.polymer-project.org/1.0/docs/devguide/data-binding.html#attribute-binding (9认同)
  • 实际上,我不得不使用`Polymer.dom(e).path [2] .getAttribute('data-args')`.请参阅:https://www.polymer-project.org/1.0/docs/devguide/events.html#retargeting接受了答案! (5认同)

小智 45

经过大量的搜索,我发现了我认为最干净的解决方案.

如果纸张按钮位于模板内,例如

<template is="dom-repeat" items="{{allItems}}" as="item">
 <paper-button on-tap="itemTapped">[[item.text]]</paper-button>
</template>
Run Code Online (Sandbox Code Playgroud)

然后可以通过传递给function的事件对象中的"model"属性访问属性.

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'));
}
Run Code Online (Sandbox Code Playgroud)

  • 实际上这是使用Polymer 1.7.0 API的正确答案,之前的答案现已过时 (3认同)
  • 这实际上是Polymer> = 1.x的正确版本因此,根据Polymer docs,这个应该被标记为正确 (3认同)

Jac*_*ips 9

更多地阐述了上述评论中提到的细微差别.

$=如果读取数据绑定,则必须使用通知.

<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;
}
Run Code Online (Sandbox Code Playgroud)

在里面dom-repeat,item(或给你的名字)可在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;
}
Run Code Online (Sandbox Code Playgroud)