Binding to a method using Polymer
-
21-12-2019 - |
Question
When using Polymer, is it possible to bind to a method rather than a value? E.g.
<div>{{someMethod()}}</div>
or
<div>{{someMethod}}</div>
Judging from the source and docs, it is not. Just wanted to confirm.
Solution
Not directly, but there are a couple of ways to probably achieve what you want. I'm assuming you want to transform data...?
Define a property as an ES5 getter
A bit of a cheat, but you can define a property as a getter and then wrap custom logic around the value that's returned.
<div>{{likes}}</div> Polymer('my-tag', { firstName: 'John', get likes() { return this.firstName + ' ' + lastName + ' likes bread'; } });
Demo: http://jsbin.com/nuyuqote/3/edit
Note: Use this optional cautiously. Binding to a getter doesn't work under
Object.observe()
, which Polymer will use if supported. See Scott's comment below.Custom filters
Not documented yet :(
<div>{{'thingy' | upperCaseFilter}}</div> Polymer('my-tag', { upperCaseFilter: function(value) { return value.toUpperCase(); } });
<prop>Changed
See Scott's comment below.
BTW, one reason we don't have something like {{someMethod()}}
in Polymer is that that executes JavaScript. It's generally considered an anti-pattern to do something like onclick="someMethod()"
because it's easy to subject yourself to things like XSS attacks.