Javascript OOP events

Javascript OOP events

本文关键字:events OOP Javascript      更新时间:2023-09-26

我想创建一个可以解析特定文件类型的对象。我已经查看了File API中的一些文件,我希望我的对象工作起来大致相同。基本上,我想要的是:

一个函数,称为CustomFileParser。我希望能够像下面这样使用它:

var customFileParser = new CustomFileParser();
customFileParser.parsed = paresed;
customFileParser.progress = progress;
customFileParser.parse(file);
function parsed(event){
 //The file is loaded, you can do stuff with it here.
}
function progess(event){
 //The file load has progressed, you can do stuff with it here.
}

所以我在考虑如何定义这个对象,但我不确定如何定义这些事件以及我应该如何做。

function customFileParser(){
 this.parse = function(){
  //Do stuff here and trigger event when it's done... 
 }
}

然而,我不确定如何定义这些事件,以及如何做到这一点。有人能帮我一下吗?

javascript是一种基于原型的OOP语言,不像大多数流行语言那样基于类。因此,OOP结构与您可能习惯的稍有不同。您应该忽略大多数试图在JS中实现基于类的继承的网站,因为这不是该语言的使用方式。

人们这样做的原因是因为他们习惯了基于类的系统,通常甚至不知道还有其他选择,所以他们不是试图学习正确的方式,而是试图实现他们更熟悉的方式,这通常会导致大量的hack或外部库,这些基本上是不必要的。

就用原型吧。

function CustomFileParser(onParsed, onProgress) {
    // constructor
    this.onParsed = onParsed;
    this.onProgress = onProgress;
};
CustomFileParser.prototype.parse = function(file) {
    // parse the file here
    var event = { foo: 'bar' };
    this.onProgress(event);
    // finish parsing
    this.onParsed(event);
};

你可以这样使用

function parsed(event) {
    alert(event);
}
function progress(event) {
    alert(event);
}
var customFileParser = new CustomFileParser(parsed, progress);
var file = ''; // pseudo-file
customFileParser.parse(file);

从我听来,我认为你需要你的程序看起来像这样

function customFileParser( onparse , progress){
this.onparse = onparse;
this.progressStatus = 0;
this.progress = progress;
this.parser = function (chunk) 
}
this.parse = function(){
// Do stuff of parsing

// Determine how much data is it
// Now make a function that parses a bit of data in every run
// Keep on calling the function till the data is getting parsed
// THat function should also increase the percentage it think this can be done via setTimeout.
// After every run of the semi parser function call the progress via something like
this.parser();
if(progressStatus <100){
this.progress(this.progressStatus);
}else{
 this.parsed();
 }
}
}

和u可以创建该对象的实例,如

 var dark = new customFileParser( function () { // this tells what to
    do what parsed is complete  } , function (status) { // this tells what
    to do with the progress status } ) ;

使用我建议的方法。你可以为你拥有的对象的所有实例定义不同的方法!