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

爱⌒轻易说出口 提交于 2019-12-22 00:27:08

问题


As far as my Polymer knowledge goes I can

  • bind a function using the "on-*" syntax to a webcomponent method

  • bind a function available in the global window namespace using vanilla html js binding (using onClick="...")

But I want to bind a function (provided as property of datamodel objects) to the webcomponent template. One sidenote : Moving the datamodel objects to the global javascript namespace (i.e. window.*) is not an option.

The example below does'nt work but reflects exactly my use case :

...
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>
... 

one more question if someone has an idea how to solve the question above) : how can i provide additional arguments to function ?

Any help is appreciated :-)


回答1:


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



来源:https://stackoverflow.com/questions/28364296/how-can-i-bind-a-dynamic-function-within-a-polymer-component

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