使用事件侦听器

时间:2017-09-19 12:50:39

标签: javascript

我正在构建一个简单的绘图应用程序。 我们说我有4个班级:

App.js handles the communication between the classes
Pixels.js stores the image data
Display.js displays the data
Load.js loads in data

通常在App类中,我可以做类似

的事情
$('#icon-flip').mouseup((e) =>
{
  this.pixels.flip_pixels();
  this.display.update(this.pixels.get_pixels());
});

现在我已经添加了一个Load类,我的问题是我不知道如何让App类知道数据已经完全加载和处理,因为Load类不应该知道App类。

这是Load类

class Load
{

  constructor(config)
  {
    this.config = config;
    this.setup_load_input();
  }

  setup_load_input()
  {
    let element = document.createElement('div');
    element.innerHTML = '<input type="file" id="input-load" style="display: none">';
    let fileInput = element.firstChild;
    document.body.append(fileInput);
    var that = this;
    fileInput.addEventListener('change',function() {  that.read_file_data(fileInput); });
  }

  read_file_data(fileInput)
  {
    var file = fileInput.files[0];

      if (file.name.match(/\.(spm|json)$/)) 
      {
        var reader = new FileReader();
        reader.onload = () => 
        {
          this.parse_file(reader.result);
        };
        reader.readAsText(file);    
      } else {
          alert("File not supported, .spm or .json files only");
      }
  }


  parse_file(file) 
  {
    this.imported_file = JSON.parse(file);
  }

  get_imported_file()
  {
    return this.imported_file;
  }

}

我使用

从App类触发它
$('#icon-load').mouseup((e) =>
{
  $("#input-load").trigger("click");
});

加载并解析数据后,我需要

this.pixels.update(this.load.get_imported_file());
this.display.update(this.pixels.get_pixels());

但我不知道如何做到这一点,因为我不知道Load类何时完成数据处理。我认为解决方案可能是一个回调,但由于我是一个菜鸟,我不知道如何。

我很抱歉长篇帖子和糟糕的代码质量。感谢您提供任何有用的支持!

1 个答案:

答案 0 :(得分:1)

您可以将事件处理程序传递给/* App.js */ function updateThings() { this.pixels.flip_pixels(); this.display.update(this.pixels.get_pixels()); } // then later... new Load({ onLoad: updateThings.bind(this) }); /* Load.js */ // In read_file_data()... reader.onload = () => { this.parse_file(reader.result); this.config.onLoad(); }; 吗?例如:

{{1}}
相关问题