In the following code, I want to use a function as a condition attribute:
<polymer-element name="test-element">
<template>
<select id="type_menu" on-change="{{ onSelected }}">
<option value="0" disabled?="{{ isDisabled }}">Item 0</option>
<option value="0" disabled?="{{ isDisabled }}">Item 1</option>
<option value="0" disabled?="{{ isDisabled }}">Item 2</option>
</select>
</template>
<script>
Polymer('test-element', {
onSelected: function(event, details, sender) {
// do something here
},
isDisabled: function() {
return false; // simplified here - it doesn't matter, it always returns true
}
}
</script>
</polymer-element>
So far, I have not been able to make this work. I have tried using disabled?="{{ isDisabled() }}" also. Can it be done at all? If not, what is the best way to do this with some kind of function? Setting a data property on ready might work but it seems a bit unwieldy.
Here is an example of how I solved it:
<polymer-element name="test-element">
<template>
<select id="type_menu" on-change="{{ onSelected }}">
<option value="0" disabled?="{{ someData[0].val | isDisabled }}">Item 0</option>
<option value="1" disabled?="{{ someData[1].val | isDisabled }}">Item 1</option>
<option value="2" disabled?="{{ someData[2].val | isDisabled }}">Item 2</option>
</select>
</template>
<script>
Polymer('test-element', {
ready: function() {
// in this case, I'm just using read to put in some simple values to filter
this.someData = [{
val = 0
},{
val = 1
},{
val = 2
}];
},
onSelected: function(event, details, sender) {
// do something here
},
isDisabled: function(val) {
return val < 2;
}
}
</script>
</polymer-element>
This is a very simple example, but the gist is this:
The conditional attribute binding ( disabled? = {{ }} ) expects a value ( {{ value }} ) or a value and a filter separated by a pipe ( {{ value | filter }} ). If you give it a function as the value, I believe it evaluates the truthiness of the function directly (does not run it) - ie someFunctionName == true as opposed to someFunctionName() == true. In that context, someFunctionName will always be truthy because it's evaluating the existence of the function (not undefined or not null, etc.) as opposed to a value the function might return.
In the fix, I'm using a filter, which IS evaluated as a function return (and is passed the value). If, in the fix shown here, I were only to include the value, the first option would be disabled and the others would be enabled (because 0 is falsey). If I pass it the filter, though, the function can evaluate the value based upon its algorithm.
This really becomes useful when you're using an inner template with a loop to populate some list based upon data and you want to set disabled, selected, (whatever) dynamically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With