如何构建一个接受回调对象的javascript类

How to build a javascript class which accept a callback object

本文关键字:对象 回调 javascript 何构建 构建 一个      更新时间:2023-09-26

让我们假设我想创建一个javascript类/对象/函数,它有一个方法,可以接受一个回调对象,像这样:

callbacks = {
   onSuccess : // method to be executed in case of success
   onComplete : // method to be executed in case of complete
   onFailure : // method to be executed in case of failure
   onError : // method to be executed in case of an error
}

那么我们假设类的名称定义如下:

var Obj = function () {};
Obj.prototype.exec = function (callbacks, event, caller, argument) {
}

我想这样使用这个对象:

var mytest = new Test();
var myObj = new Obj();
Obj.exec(callbacks,["onSuccess", "onComplete"], mytest, arguments);

Obj.prototype.exec应该如何实现?

你的问题有点让人困惑:

Obj.prototype.exec = function (callbacks, event, caller, argument) {
    var $xhr;
    if (argument instanceof Array)
        $xhr = caller.ajax.apply(this, argument)
    else
       $xhr = caller.ajax.call(this, argument)
    // wire up the listeners
    for (var i = 0; i < event.length; i++) {
        $xhr[event[i]] = callbacks[event[i]];
    }
}

像这样的