根据数组突变事件和另一个属性定义Polymer计算属性

时间:2016-07-30 20:00:23

标签: javascript polymer

我试图定义一个取决于数组突变事件和另一个自定义属性的计算聚合物属性。由于某种原因,聚合物不会调用计算函数,但是当我删除两个依赖项中的一个时,一切都像魅力一样。

item: {
    type: Object,
    value: {
        votes: []
    }
},
authId: {
    type: String,
    value: '123'
},
voted: {
    type: Boolean,
    notify: true,
    computed: 'computeVoted(item.votes.*, authId)'
}

编辑:由于一些误解而更新了示例

2 个答案:

答案 0 :(得分:2)

对我来说很好。您是否发现了以下片段中的差异?

Polymer({
  is: 'my-elem',
  
  properties: {
    prop: {
      type: String,
      value: 'prop'
    },
    array: {
      type: Object,
      value: {
        items: []
      }
    },
    computed: {
      computed: 'compute(array.items.*, prop)'
    }
  },
  
  mutateArr: function() {
    this.push('array.items', 'arr');
  },
  
  compute: function(arr, prop) {
    return prop + ';' + arr.base.length;
  }
});
<!DOCTYPE html>
<html>
<head>
  <base href="https://polygit.org/components/">
  <script src="webcomponentsjs/webcomponents-lite.min.js"></script>
  <link href="polymer/polymer.html" rel="import"/>
</head>

<body>
  <my-elem></my-elem>
  
  <dom-module id="my-elem">
    <template>
      <input type="button" value="Mutate array" on-tap="mutateArr" />
      <input type="text" value="{{prop::input}}" />
      <br/>
      <span>{{computed}}</span>
    </template>
  </dom-module>

</body>
</html>

答案 1 :(得分:0)

以下是您要实现的目标的示例。始终建议您初始化observerscomptuted设置的值。

&#13;
&#13;
<base href="http://polygit.org/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<link rel="import" href="polymer/polymer.html">

<dom-module id="button-group">
  <template>
    <style></style>
    <div on-tap='changeAuthId'>Change AuthId</div>
    <div on-tap='changeItem'>Change item</div>
    {{voted}}
  </template>
</dom-module>
<script>
  Polymer({
    is: 'button-group',
    properties: {
      item: {
        type: Object,
        value: function() {
          return {
            votes: [{
              one: 'one'
            }, {
              two: 'two'
            }]
          }
        }
      },
      authId: {
        type: String,
        value: 'test'
      },
      voted: {
        type: String,
        notify: true,
        computed: 'computeVoted(item.votes.*,authId)'
      }
    },
    computeVoted: function(firstVal, authId) {
      //firstVal will be an Object containing three variables 
      //base: which will have item.voted object
      //path: which will contain path of changed value/s
      //value: which will contain new value/s
      return 'Path for changed value: ' + firstVal.path + ' AuthId: ' + authId
    },
    changeAuthId: function() {
      this.authId = "new id"
    },
    changeItem: function() {
      var three = {
        three: 'three'
      };
      this.set('item.votes.0', three);
    }
  });
</script>


<button-group></button-group>
&#13;
&#13;
&#13;