使用 addEventListener 加载文件

load file with addEventListener

我使用 Backbone 在我的应用程序中创建一个菜单,我可以在其中打开一个项目:

app.Tools = Class.extend({

  init: function(elementId, app, view) {
    this.html = $("#" + elementId);
    this.view = view;
    this.app = app;  

    this.openButton = $('<li><button data-toggle="modal" data-target="#openProject" class="btn btn-primary nav-item nav-link" title="Open"><i class="glyphicon glyphicon-folder-open" aria-hidden="true"></i></button></li>');
    this.html.append(this.openButton);
    this.openButton.click($.proxy(function(){
      if (!document.getElementById('openProject')) {
        //modal view to confirm new project
        this.html.append(
          `<div class="modal fade" id="openProject" tabindex="-1" role="dialog">
              <div class="modal-dialog">
                 <div class="modal-content">
                    <div class="modal-header">
                       <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                       <h4 class="modal-title">Open a project</h4>
                    </div>
                    <div class="modal-body">
                       <span class="glyphicon glyphicon-warning-sign"></span> <p>Are you sure you want to do this? If you didn\'nt save your actual project, all your work will be lost for ever.</p>
                    </div>
                    <div class="modal-footer">
                       <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                       <span class="btn btn-primary btn-file">Open project<input id="open-project-butt" type="file" class="btn btn-primary"></span>
                    </div>
                 </div>
              </div>
           </div>`
        );
     };

     //listen for new inputs
     document.getElementById('open-project-butt').addEventListener('change', readSingleFile, false);

     function readSingleFile() {
       $('#openProject').modal('hide');
         app.view.clear();
         newProject(app.view);

         var file = this.files[0];
         if (!file) {
           return;
         }

         var reader = new FileReader();
         reader.onload = function() {
           //parse result of the upload
           var parsed = new DOMParser().parseFromString(this.result, "text/xml");
           var stringXML = (new XMLSerializer()).serializeToString(parsed);
         }
       }
       reader.readAsText(file);
     }
   },this));
  }
});

我第一次打开文件时一切正常。问题是 readSingleFile() 函数被调用的次数与我打开的文件一样多。

我创建了一个 codepen,但没有 Backbone 也能正常工作。

有任何帮助或解决问题的线索吗?谢谢

好吧,你的错误是在单击按钮时在函数内部添加了事件侦听器。您应该将其移出点击处理程序。

每次点击都会添加一个新的监听器。点击多少次,函数就会被调用多少次。