-->

Polymer 1.x: How to data bind to a variable boolea

2019-08-09 09:40发布

问题:

Question

How do I bind a variable to/as the disabled attribute of a <paper-checkbox> element?

Based on the results of my code, it looks like the only way to toggle the disabled property is to include the disabled attribute as a string in the start tag. Surely there must be a way to toggle that as a variable?

Link to JSBin

http://jsbin.com/zecidojizu/edit?html,output
<!DOCTYPE html>
<html>  
<head>
  <meta charset="utf-8">
  <title>Polymer Bin</title>
  <base href="http://element-party.xyz/">
  <script src="bower_components/webcomponentsjs/webcomponents-lite.js"></script>
  <link rel="import" href="all-elements.html">
</head>
<body>
<x-element></x-element>
<dom-module id="x-element">
  <template>
    <style>
      paper-checkbox {
        display: block;
        margin-bottom: 30px;
      }
    </style>
    <paper-checkbox                  >A</paper-checkbox>
    <paper-checkbox  disabled        >B</paper-checkbox>
    <paper-checkbox xdisabled        >C</paper-checkbox>
    <paper-checkbox  disabled=true   >D</paper-checkbox>
    <paper-checkbox  disabled="true" >E</paper-checkbox>
    <paper-checkbox  disabled=false  >F</paper-checkbox>
    <paper-checkbox  disabled="false">G</paper-checkbox>
    <paper-checkbox  [[bool]]        >H</paper-checkbox>
    <paper-checkbox "[[bool]]"       >I</paper-checkbox>
    <paper-checkbox  {{bool}}        >J</paper-checkbox>
    <paper-checkbox "{{bool}}"       >K</paper-checkbox>
  </template>
  <script>
    (function(){
      Polymer({
        is: 'x-element',
        properties: {
          bool: {
            type: String,
            value: 'disabled'
          }
        }
      });
    })();
  </script>
</dom-module>
</body>
</html>

回答1:

You need to bind the attribute like so: disabled=[[bool]]. This is the equivalent of calling element.disabled = bool where element is some instance of paper-checkbox.

See this forked JSBin for an example.

Basically a Boolean HTMLAttribute will be true if that attribute exists, and false if it does not exist. So for:

<paper-checkbox disabled="[[isDisabled]]"></paper-checkbox>

The output HTML will look like this:

<paper-checkbox disabled></paper-checkbox>

when isDisabled is true, and look like this:

<paper-checkbox></paper-checkbox>

when isDisabled is false.

That's why setting

<paper-checkbox disabled="false"></paper-checkbox>

will still make the checkbox disabled.

See the last paragraph in Polymer's Documentation on Attribute Deserialization



回答2:

disabled is a native HTML attribute. To bind to native attributes, you must use $= instead of =.

<paper-checkbox disabled$="{{isDisabled}}">Foo</paper-checkbox>


回答3:

Haven't you left out disabled$={{Boolean}}?