Polymer 1.0 boolean property having default value set to true
Asked Answered
D

1

6

I have a Polymer 1.0 custom element that has a property of type boolean with default value set to true:

    myProperty: {
        type: Boolean,
        value: true
    }

In my unit-test I instantiate this custom element with my-property set to false:

<my-custom-element id="myElem" my-property="false"></my-custom-element>

 var elem = document.getElementById('myElem');

 test('it_should_set_myProperty_to_false', function () {
     assert.equal(elem.myProperty, false);
 })

The unit-test is failing. elem.myProperty is actually set to true when I would expect it to be false. Why is this?

Damales answered 2/7, 2015 at 9:14 Comment(0)
C
13

The behavior of boolean properties has changed in Polymer 1.0 and now follows the specification of HTML boolean attributes. The property is set to true if the attribute exists on the element (regardless of the attribute value) and no deserialization happens if the attribute is not specified. So you can't set a boolean property to false if it was initially true.

You can only set the default value of the property to false

myProperty: {
   type: Boolean,
   value: false
}

and then set the attribute to make myProperty true.

<my-element my-property></my-element>

This topic is discussed in some issues of the Polymer project, for example here and here.

The second issue also mentions a workaround by using a property of type Object. Because these properties are deserialized with JSON.parse you can specify a boolean value with my-property="false" and my-property="true".

Canso answered 2/7, 2015 at 11:49 Comment(1)
Interesting! Thanks for your detailed response.Damales

© 2022 - 2024 — McMap. All rights reserved.