Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hidden attribute in Polymer 1.0

I haven't used Polymer since the 0.4-0.5 era and am used to using the hidden attribute like so <my-element hidden="{{foo != bar}}"></my-element>

Now in Polymer 1.0 I see that have to use computed values from a method for anything that is not straight up a boolean value. I have my code like this:

<my-element hidden="{{_computeHidden()}}"></my-element>

And then in the script section:

Polymer({
    is: 'super-element',
    properties: {...},
    _computeHidden: function(){
         console.log('its being called, mkay');
         return !(foo == bar);
    }
});

Now in the console the message comes up twice after page refresh but when the value of foo changes, the element does not disappear. What am I doing wrong?

like image 998
najm Avatar asked Aug 23 '15 17:08

najm


2 Answers

If you want to trigger the recalculation of your function when foo changes, you have to ensure that foo is property and pass it into the function as an argument. Here's a small example.

<dom-module id="register-me">
    <template>
        <div hidden$="{{compute(ishidden)}}">Hello from my local DOM</div>
        <button on-click="toggle">Toggle Hidden</button>
    </template>
    <script>
        Polymer({is: "register-me",
            properties: { ishidden: {
                type: Boolean,
                value: false
            } },
            compute: function() {
                console.log("computing...");
                return this.ishidden;
            },
            toggle: function() {
                this.ishidden = !this.ishidden;
            }
        });
    </script>
</dom-module>

Note that to bind to attributes, you should use $=.

like image 36
Maria Avatar answered Oct 19 '22 04:10

Maria


So, there are two issues. As Maria notes, you have to have your _computeHidden method bound to parameters that will respond to Polymer notifications. So, both foo and bar must be declared as properties on the element.

Another issue is that "hidden" is a boolean attribute, meaning that its very presence indicates that the element should be hidden. In Polymer 1.0, using $ in hidden$= changes hidden into a property binding and will handle strings. Without $, hidden= will evaluate just raw boolean. hidden is not on the list for required $ in native html attributes, so the choice is up to you.

Polymer({
    is: 'my-element',
    properties: {
      foo: Boolean,
      bar: Boolean
    },
    _computeHidden: function(){
      return !(this.foo == this.bar);
    }
});
<my-element hidden$="{{_computeHidden(foo, bar)}}"></my-element>

With this annotated attribute binding, "hidden" will appear on the element only if your computed value is truthy, which is the behavior you want. With a simple "=" binding, "hidden" will appear even if your function returns true, or null, or any other value.

like image 161
Eric Nguyen Avatar answered Oct 19 '22 05:10

Eric Nguyen