Asked By: Anonymous
I’m have a polymer element whose model may be one of two classes (technically one of two subclasses of a common superclass). I’m looking for my element template to be slightly different depending on which of the two classes the model is. Something like this:
<polymer-element name="my-element">
<template>
{{model.runtimeType}} <!-- sanity check -->
{{model.commonProperty}}
<template if="{{model is Foo}}">
{{model.fooSpecificProperty}}
</template>
<template if="{{model is Bar}}">
{{model.barSpecificProperty}}
</template>
</template>
<a href="http://my-element.dart">http://my-element.dart</a>
</polymer-element>
What I’m finding is that both of the if templates are displaying, as though both model is Foo
and model is Bar
are returning true. For each type of model, I see that the {{model.runtimeType}}
is printing Foo
and Bar
as appropriate.
I’ve also tried changing the if conditions to other things such as {{model.runtimeType.toString() == 'Foo'}}
, but I can’t seem to find the right condition to properly sort out my model types.
In a Dart Polymer element, what is the correct way to detect and filter based on the type of an object?
EDIT: Also noticing that both {{model is Foo}}
and {{model is! Foo}}
seem to return true as a conditional when used in Polymer, but work as expected inside a .dart file.
Solution
Answered By: Anonymous
It’s important not to use toString()
here, since it will not work when using dart2js with minification. Similar to the other suggestions, here are two ideas that should work even with obfuscation/minification.
<polymer-element name="x-tag">
<template>
<!-- idea #1 -->
<template if="{{model.runtimeType == fooType}}"> ...
<!-- idea #2 -->
<template if="{{isFoo}}"> ...
and
@CustomTag(x-tag)
class XTag extends PolymerElement {
// idea #1
Type get fooType => Foo;
// idea #2
@observable bool isFoo;
@ObserveProperty('model')
updateIsFoo() { isFoo = model is Foo; }
}