2016-05-06 106 views
5

我有这个简单的元件,它只是让你一次选择一个本地文件,然后显示选定的文件,你可以删除项目,这样的事情: enter image description here多个实例

组件本身工作得很好,问题是我在同一页面中有另一个相同类型的组件,但是在不同的父元素(和隐藏的)中。如果我在第一个文件选择器上选择了n个文件,然后切换到查看其他父组件,这第二个文件选择器在其中显示与第一个文件选择器相同的文件。

如果我把这两个文件组件放在同一个父元素中,在其中一个文件中选择一个文件不会在另一个文件中显示相同的文件,但是从其中移除一个文件会使组件文件数组财产(我存储每个文件的选择)在他们两个都较短,最终导致无法从其中之一移除项目。

我asume我的问题与某种方式封装有关,但无法弄清楚为什么。这是我的组件代码:

<dom-module id="custom-file-input"> 
<style> 
    ... 
</style> 
<template> 
    <div class="horizontal layout flex relative"> 
     <button class="action" on-click="butclick" disabled$="{{disab}}">{{restexts.CHOOSEFILE}}</button> 
     <div id="fakeinput" class="flex"> 
      <template is="dom-repeat" items="{{files}}" as="file"> 
       <div class="fileitem horizontal layout center"> 
        <span>{{file.0}}</span><iron-icon icon="close" class="clickable" on-click="removeFile"></iron-icon> 
       </div> 
      </template> 
     </div> 
     <input id="fileinput" type="file" on-change="fileChanged" hidden /> 
    </div> 
</template> 
<script> 
    Polymer({ 
     is: "custom-file-input", 
     properties: { 
      files: { 
       type: Array, 
       value: [] 
      }, 
      currentFile: { 
       type: Object, 
       value: {} 
      }, 
      disab: { 
       type: Boolean, 
       value: false, 
       reflectToAttribute: true, 
       notify: true 
      }, 
      restexts: { 
       type: Object, 
       value: JSON.parse(localStorage['resourcesList']) 
      } 
     }, 
     fileChanged: function (e) { 
      this.currentFile = e.currentTarget.files[0]; 
      var elem = this; 

      var fr = new FileReader(); 
      fr.readAsArrayBuffer(this.currentFile); 
      fr.onload = function() { 
       [...convert file to string64...] 
       elem.push('files', [elem.currentFile.name, string64]); 
      }; 
     }, 
     removeFile: function (e) { 
      for (var i = 0; i < this.files.length; i++) { 
       if (this.files[i] == e.model.file) { 
        this.splice('files', i, 1); 
        break; 
       } 
      } 
     }, 
     butclick: function() { 
      this.$.fileinput.click(); 
     } 
    }); 
</script> 
</dom-module> 

回答

9

当初始化属性对象或数组值,使用的功能,以确保每个元素都有自己的价值的副本,而不是一个对象或数组在所有元素实例之间共享。

来源:https://www.polymer-project.org/1.0/docs/devguide/properties.html#configure-values

{ 
    files: { 
    type: Array, 
    value: function() { return []; } 
    }, 
    currentFile: { 
    type: Object, 
    value: function() { return {}; } 
    }, 
    restexts: { 
    type: Object, 
    value: function() { return JSON.parse(localStorage['resourcesList']); } 
    } 
} 
+1

这是我第一次不得不做这样的事情是这样的工作。 谢谢:) – Iskalla