从 Javascript 库调用的事件

Events called from Javascript library

本文关键字:事件 调用 Javascript      更新时间:2023-09-26

我目前正在编写Javascript上传库,我想在几个网站上使用它,我有自己的对象Data其中包含文件,元数据等。

Data具有名为.send()的函数,该函数使用XMLHttpRequest上传FormData

我的目标是创建进度条,'progress'上有EventListener。但我不知道哪种方法是正确的,因为我不知道进度条的位置将如何在每页的 HTML 中命名。而且我还不想有任何HTML代码,只想让我自定义它。

我应该如何应对这种情况?

我当前的代码:

Data.prototype.send = function() {
  'use strict';
  var formData = new FormData();
  formData.append('file', this.file, this.name);
  if (this.property !== undefined) {
    formData.append('property', this.property);
  }
  var request = new XMLHttpRequest();
  request.upload.addEventListener('progress', function(e) {
    var pc = parseInt(100 - (e.loaded / e.total * 100));
    //What to do here?
  }, false);
  request.onreadystatechange = function(e) {
    if (xhr.readyState == 4) {
      //What to do here?
    }
  };
  request.open('POST', upload.php, true);
  request.send(formData);
};

向 send() 方法添加回调是一种可能的解决方案。然后,使用上传小部件的每个页面都可以接收进度事件,以更新其 UI。 您还可以预处理事件以返回简单的完成百分比。下面的示例显示了这两种方法。

此外,"

onloadstart"、"onprogress"和"onloadend"都返回相同的事件类型,但在上传周期的不同点。 因此,使用单个处理程序组合所有三个可能很有用(如图所示)。

根据我的经验,并非所有浏览器都返回相同的属性或在上传周期中同时返回。因此,您可能需要进行一些实验才能使其正常工作。更有用的属性是:iscomputable,total,totalSize,loaded,position。 更多信息在这里 MDN.

Data.prototype.send = function( callback ) {
    // 1. forward raw event to page handler 
    request.upload.onloadstart = 
      request.upload.onprogress = 
        request.upload.onloadend = callback;
    // 2. alternative - process event and return percent to page handler
    request.upload.onloadstart = 
      request.upload.onprogress = 
        request.upload.onloadend = function(e) {
            var pc = parseInt(100 - (e.loaded / e.total * 100));
            if (typeof callback == 'function') callback( pc );
    }