具有默认值的聚合物对象属性

Pet*_*ter 6 polymer

我想在我的自定义元素中设置一个选项对象属性,该属性在用户不提供时将采用默认值.

<!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>
Run Code Online (Sandbox Code Playgroud)

上面的代码不起作用,因为元素构造函数中指定的值总是覆盖我试图传入的值.如何设置它以便将选项值设置为传入的值,默认值仅用作后备?

Sco*_*les 6

您可以使用属性中的JSON将对象值传递到已发布的属性,但它必须是严格有效的JSON(http://jsonlint.com/).

在这种情况下,请尝试:

<my-element options='{
            "option_1": "val1",
            "option_2": "val2",
            "allow_this": true,
            "allow_that": false
        }'>
</my-element>
Run Code Online (Sandbox Code Playgroud)

注意属性上的单引号和JSON本身内的双引号.JSON规范要求使用双引号.

请注意,这不是数据绑定,因此它不使用胡子符号{{ }}.相反,您只是简单地描述Polymer将反序列化(JSON.parse)到对象中的属性中的字符串值.