Friday, June 12, 2015

Polymer Quicktip - Attributes vs. Properties

A recurring problem that people starting with Polymer 1.0 or migrating from earlier version seem to have is the new property name to attribute name mapping.

This issue imho comes mainly from the fact that the element docs generated via iron-component-page only list the JS property names, but in many/most cases you will use the HTML attribute names in your markup that aren't listed anywhere.

Example from the google-signin element:


If you try to include this element in your page like this

<google-signin clientId="MY_CLIENT_ID"></google-signin>

it won't work because the clientId attribute will be mapped to a clientid property that doesn't exist and clientId will stay undefined.

The correct way to use the element would be:

<google-signin client-id="MY_CLIENT_ID"></google-signin>

So if you encounter issues with properties not getting the value you intended make sure your attribute names are correct.

Essentially the attribute name is converted to lower case first, and then dashes are converted to camelcase, SoMeThInG becomes something and SoMeThInG-ElSe becomes somethingElse.

For those interested, here's the part of the Polymer library that takes care of translation between attribute names and property names:
https://github.com/Polymer/polymer/blob/master/src/lib/case-map.html

And if you are really curious you can have a look at Polymer.CaseMap._caseMap to see what mappings are being used on your site.