聚合物自定义元素属性为布尔类型值

时间:2014-07-09 00:51:32

标签: polymer

虽然Demo A有效,但我想了解是否可以使其像Demo B一样有效。基本上,要将自定义元素解析为happyFlag属性为布尔类型。

// Demo A - works. bob smiles. cat frowns.
<x-smiley name="Bob" happyFlag="true"></x-smiley>
<x-smiley name="Cat" happyFlag="false"></x-smiley>
<polymer-element name="x-smiley" attributes="name, happyFlag" noscript>
    <template>
        {{name}} is
        <span hidden?="{{happyFlag == 'true'}}">:-)</span>
        <span hidden?="{{happyFlag == 'false'}}">:-(</span>
        <hr>
    </template>
</polymer-element>

// Demo B - does not work (span always hidden)
<x-smiley name="Bob" happyFlag="true"></x-smiley>
<x-smiley name="Cat" happyFlag="false"></x-smiley>
<polymer-element name="x-smiley" attributes="name, happyFlag" noscript>
    <template>
        {{name}} is
        <span hidden?="{{happyFlag}}">:-)</span>
        <span hidden?="{{happyFlag}}">:-(</span>
        <hr>
    </template>
</polymer-element>

1 个答案:

答案 0 :(得分:7)

您可以为Polymer提供有关属性输入类型的提示。请参阅以下示例,其中我添加了Polymer脚本,特别是创建的方法中的this.happyFlag = false。此行为Polymer提供了一个提示,即该值应视为布尔值。有关提示类型,请参阅Polymer's Documentation

<polymer-element name="x-smiley" attributes="name, happyFlag">
<template>
    {{name}} is {{happyFlag}}
    <span hidden?="{{happyFlag}}">:-)</span>
    <span hidden?="{{happyFlag}}">:-(</span>
    <hr>
</template>
<script>
  Polymer('x-smiley', {
    created: function() {
        this.happyFlag = false;
    },
    ready: function() {
    }
  })
</script>