Polymer Object Attribute with Default Values

I want to set the attribute of the options object in my user element, which will take default values ​​if they are not provided by the user.

<!DOCTYPE html> <html> <head> <script src="bower_components/platform/platform.js"></script> <link rel="import" href="bower_components/polymer/polymer.html"> </head> <body> <my-element options="{{{ option_1: 'val1', option_2: 'val2', allow_this: true, allow_that: false }}}"> </my-element> </body> </html> <polymer-element name="my-element" attributes="options"> <template> <ul> <!-- ... --> </ul> </template> <script> Polymer('my-element', { options: { option_1: 'default_val1', option_2: 'default_val2', allow_this: false, allow_that: false } }); </script> </polymer-element> 

The above code does not work, because the values ​​specified in the element constructor always override the ones I'm trying to pass. How can I configure it so that the parameter values ​​are set to those that were transferred, and the default values ​​are used only as a fallback?

+7
polymer
source share
2 answers

You can pass values ​​of objects to published properties using JSON in attributes, but it must be strictly valid JSON ( http://jsonlint.com/ ).

In this case, try:

 <my-element options='{ "option_1": "val1", "option_2": "val2", "allow_this": true, "allow_that": false }'> </my-element> 

Notice the single quotation marks in the attribute and the double quotation marks inside the JSON itself. Double quotes are required by JSON specifications.

Note that this is not data binding, so it does not use mustache notation {{ }} . Instead, you simply describe the string value in the attribute that the Polymer will deserialize ( JSON.parse ) into an object.

+7
source share

Data binding does not work outside polymer elements. Either use the auto-link template element or wrap the use of my element in another custom Polymer element.

But then you get a parsing error to express your options. You need to put spaces around the object bindings: options="{{ { ...} }}" .

You should also check the warning in the section Adding General Properties and Methods in Polymer Docs on Initializing Array and Object Properties.

+3
source share

All Articles