如何触发Polymer中的attributeChanged-Function

时间:2015-01-09 12:01:05

标签: javascript polymer

我有一个像这样的简单的Polymer canvas对象:

<polymer-element name="canvas-diagram" attributes="type width height json">
  <template>
    <div id="canvasField">
        Typ: {{type}}, Width:<input value="{{width}}">, Height:{{height}}, json:{{json}}
        <div id="canvasContainer">
            <canvas id="canvasObj" width="{{width}}" height="{{height}}"></canvas>
        </div>    
    </div>
  </template>
  <script>
      function getMaxOfArray(numArray) {
        return Math.max.apply(null, numArray);
    }
    Polymer("canvas-diagram",{
        type: "bar",
        width: "300",
        height: "200",
        ready: function() {
             console.log("this.ready()");
            this.writeDiagram();
        },
        attributeChanged: function(attrName, oldVal, newVal) {
            console.log("this.attributeChanged()");
            console.log(attrName, 'old: ' + oldVal, 'new:', newVal);
            this.writeDiagram();
        },
        writeDiagram : function(){
           [...]
        },

      json: {
        data:[
            {"name":"Texts","value":"150"},
            {"name":"Videos","value":"50"},
            {"name":"Audio","value":"30"},
            {"name":"Test","value":"20"},
            {"name":"Test","value":"20"},
            {"name":"Test","value":"20"}
        ]}
    });
  </script>
</polymer-element>

但是当我手动设置属性时,attributeChanged()函数不会触发。我究竟做错了什么?我认为那是一个有条件的输入。当我从canvas-diagram-Element更改Attricute时,更改它也不会触发Function ald。

1 个答案:

答案 0 :(得分:0)

这取决于属性的变化。我不认为有一种全球方式来检查所有归因于变化。我很确定你必须通过它自己检查每个属性进行更改。例如,如果我想知道元素的type属性何时发生变化,我将使用类似的函数。

typeChanged: function () {
  console.log(this.type);
}

然后,您需要为每个属性创建一个类似上面的函数,您需要在更改时触发函数。

编辑:下面是我能想到的最简单的例子。该按钮将更改元素的text属性,更改将触发将触发警报的textChanged函数。

http://plnkr.co/edit/7swMG6dwMqwyutwMaYfd?p=preview