I want to set up an options object attribute in my custom element that will take default values when not supplied by 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 doesn't work as values specified in the element constructor always override those I am trying to pass in. How can I set it up so that option values are set to those passed in and default values are only used as fallback?
You can pass object values into 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 quotes on the attribute, and the double quotes inside the JSON itself. The double quotes are required by the JSON specifications.
Note that this is not data-binding, and so it does not use mustache notation {{ }}
. Instead, you are simply describing a string value in an attribute that Polymer will deserialize (JSON.parse
) into an object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With