Passing a function as an attribute value

非 Y 不嫁゛ 提交于 2019-12-05 18:24:47

问题


I was wondering if it was possible to pass a function foo() as an attribute func="foo()" and have it called this.func() inside of the polymer element?

<foo-bar func="foo()"></foo-bar>


Polymer({
  is: 'foo-bar',
  properties: {
    func: Object,
  },
  ready: function() {
    this.func();
  }
});

I've been trying to get this working for ages with no luck.

Thanks in advance.


回答1:


<foo-bar func="foo()"></foo-bar>



Polymer({
  is: 'foo-bar',
  properties: {
    func: {
        type: String, // the function call is passed in as a string
        notify: true
  },
  attached: function() {
    if (this.func) {
        this.callFunc = new Function('return '+ this.func);
        this.callFunc(); // can now be called here or elsewhere in the Polymer object
  }
});

So the trick is that "foo( )" is a string when you first pass it to the Polymer element. I fought with this for a while as well and this is the only way I could find to get it done. This solution creates a function that returns your function call, which you assign as the value of one of your polymer element properties.

Some people might say you shouldn't use the Function constructor because it is similar to eval( ) and.... well you know, the whole 'eval is evil' thing. But if you're just using it to return a call to another function and you understand the scope implications then I think this could be an appropriate use-case. If I'm wrong I'm sure someone will let us know!

Here's a link to a nice SO answer about the differences between eval( ) and the Function constructor in case it can help: https://stackoverflow.com/a/4599946/2629361

Lastly, I put this in the 'attached' lifecycle event to be on the safe side because it occurs later than 'ready'. I'm not sure if an earlier lifecycle event or 'ready' could be used instead of 'attached'. Perhaps someone can improve this answer and let us know.



来源:https://stackoverflow.com/questions/31247020/passing-a-function-as-an-attribute-value

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