Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a function as an attribute value

Tags:

polymer

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.

like image 626
Flying Emu Avatar asked Jul 06 '15 13:07

Flying Emu


1 Answers

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

like image 78
CoolestUsername Avatar answered Nov 04 '22 09:11

CoolestUsername