如何让`dom-if`重新评估其`if`条件?

时间:2017-02-28 17:53:12

标签: javascript polymer polymer-1.0

在我的下面的代码中,if条件仅在init处进行评估。如果myType发生变化,如何让它重新评估条件?

<dom-module id="media-element">
  <template>
    <template is="dom-if" if="[[isType(0)]]">
      ....
    </template>
  </template>

  <script>
    Polymer({
      is: 'media-element',
      properties: {
        myType: {
          type: Number,
          value: 0
        }
      },
      isType: function(t){return (this.myType===t);}
    });
  </script>
</dom-module>

1 个答案:

答案 0 :(得分:0)

您可以像这样使用computed binding

<template is="dom-if" if="[[isType(myType, 1)]]">

HTMLImports.whenReady(() => {
  Polymer({
    is: 'media-element',
    properties: {
      myType: {
        type: Number,
        value: 0
      }
    },
    isType: function(type, val) {
      return Number(type) === Number(val);
    }
  });
});
<head>
  <base href="https://polygit.org/polymer+1.8.1/components/">
  <script src="webcomponentsjs/webcomponents-lite.js"></script>
  <link rel="import" href="polymer/polymer.html">
  <link rel="import" href="paper-input/paper-input.html">
</head>
<body>
  <media-element></media-element>

  <dom-module id="media-element">
    <template>
      <paper-input label="Movie Type (1 == mov)"
                   value="{{myType}}"
                   type="Number"
                   maxlength="1"></paper-input>
      <template is="dom-if" if="[[isType(myType, 1)]]">
        <h1>mov</h1>
      </template>
    </template>
  </dom-module>
</body>

codepen

computed property这样:

<template>
  <template is="dom-if" if="[[isMovType]]">...</template>
</template>
<script>
  Polymer({
    is: 'media-element',
    properties: {
      myType: {
        type: Number,
        value: 0
      },
      isMovType: {
        computed: 'isType(myType, 1)'  // <-- computed property
      }
    },
    isType: function(type, val) {
      return type === Number(val);
    }
  });
</script>

HTMLImports.whenReady(() => {
  Polymer({
    is: 'media-element',
    properties: {
      myType: {
        type: Number,
        value: 0
      },
      isMovType: {
        computed: 'isType(myType, 1)'
      }
    },
    isType: function(type, val) {
      return Number(type) === Number(val);
    }
  });
});
<head>
  <base href="https://polygit.org/polymer+1.8.1/components/">
  <script src="webcomponentsjs/webcomponents-lite.js"></script>
  <link rel="import" href="polymer/polymer.html">
  <link rel="import" href="paper-input/paper-input.html">
</head>
<body>
  <media-element></media-element>

  <dom-module id="media-element">
    <template>
      <paper-input label="Movie Type (1 == mov)"
                   value="{{myType}}"
                   type="Number"
                   maxlength="1"></paper-input>
      <template is="dom-if" if="[[isMovType]]">
        <h1>mov</h1>
      </template>
    </template>
  </dom-module>
</body>

codepen