如何在聚合物组件中绑定动态功能?

时间:2015-02-06 11:02:40

标签: polymer

就我的聚合物知识而言,我可以

  • 使用“on- *”语法将函数绑定到web组件方法

  • 使用vanilla html js绑定绑定全局窗口命名空间中可用的函数(使用onClick =“...”)

但我想将一个函数(作为datamodel对象的属性提供)绑定到webcomponent模板。 一个侧注:将数据模型对象移动到全局javascript命名空间(即window。*)不是一种选择。

下面的例子不起作用,但完全反映了我的用例:

...
Polymer('x-foo', {

    items : [
      ...,
      {
        label  : "ExampleCommand",
        action : function() {
            // do something
        }            
      }
      ...
    ]
})
...
<template>
    <template repeat="{{item in items}}">
        <paper-button onClick="{{item.action}}">
            {{item.label}});
        </paper-button>
    </template>
</template>
... 

如果有人知道如何解决上述问题,还有一个问题:我怎样才能提供额外的参数来运作?

感谢任何帮助: - )

1 个答案:

答案 0 :(得分:7)

我不得不向团队询问这个问题,因为它有点令人困惑。声明性事件&#34;绑定&#34;与Polymer表达式不同。不幸的是,事件绑定和Polymer表达式都使用{{ }}语法,这意味着它们的工作方式相同。他们没有。事件绑定的范围是元素本身,而表达式的范围是模板实例的模型。

在Polymer 0.8中,我认为语法已经改变,因此事件绑定不再使用{{ }}。希望这会清除它。

要获得所需的效果,您可以在元素上定义一个方法,该方法查看事件目标,获取其模型,并调用您已定义的函数。

<polymer-element name="x-foo">
  <template>
    <template repeat="{{items}}">
      <button on-click="{{doAction}}">{{label}}</button>
    </template>
  </template>
  <script>
    Polymer({
      items: [
        {
          label: 'ExampleCommand',
          action: function() {
            alert('hello world');
          }
        },
        {
          label: 'AnotherCommand',
          action: function() {
            alert('another command');
          }
        }
      ],
      doAction: function(e) {
        e.target.templateInstance.model.action();
      }
    });
  </script>
</polymer-element>

Here's the example running on jsbin