How can i bind a dynamic function within a polymer component?

放肆的年华 提交于 2019-12-04 19:37:32

I had to ask the team about this because it's kinda confusing. Declarative event "bindings" are not the same thing as a Polymer expression. Unfortunately, both event bindings and Polymer expressions use the {{ }} syntax, which implies they work the same. They don't. The scope of event bindings is the element itself, whereas as an expression is scoped to the model for the template instance.

In Polymer 0.8, I believe the syntax has changed, so event bindings no longer use {{ }}. Hopefully that will clear it up a bit.

To achieve the effect you want, you can define a method on the element, which looks at the event target, grabs its model, and calls the function you've defined.

<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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!