将函数作为属性值传递 [英] Passing a function as an attribute value

查看:70
本文介绍了将函数作为属性值传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以将函数foo()作为属性func="foo()"传递并在聚合物元素内部将其称为this.func()?

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.

提前谢谢.

推荐答案

<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
  }
});

因此,诀窍在于,当您将"foo()"首次传递给Polymer元素时,它是一个字符串.我也为此花了一段时间,这是我找到完成它的唯一方法.此解决方案创建了一个函数,该函数返回您的函数调用,您将其分配为聚合物元素属性之一的值.

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.

某些人可能会说您不应该使用Function构造函数,因为它类似于eval(),并且....众所周知,整个"eval是邪恶的"事情.但是,如果您只是使用它来返回对另一个函数的调用,并且了解范围的含义,那么我认为这可能是一个合适的用例.如果我错了,我敢肯定有人会告诉我们!

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!

以下是有关eval()和Function构造函数之间区别的一个不错的SO答案的链接,以防它有助于: https: //stackoverflow.com/a/4599946/2629361

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.

这篇关于将函数作为属性值传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆