Javascript可选参数用于回调

时间:2011-07-11 04:34:52

标签: javascript

我想做$.ajax()成功和错误回调等事情。

这是我到目前为止所做的:

var FileManager = {
            LoadRequiredFiles: function (onLoadingCallback, onCompleteCallback) {
                //Not sure what to do here
                this.OnLoading = onLoadingCallback;
                this.OnCompleteCallback = onCompleteCallback;

                this.OnLoading();
                this.OnComplete();
            },
            OnLoading: function () {
                //empty by default
            }
            OnComplete: function () {
                //empty by default
            }

};
//I want to do something like this:
FileManager.LoadRequiredFiles({OnLoading: function() {
            alert('loading');
       }
});

如何正确解决此问题?我正在使用FileManager作为我的命名空间。

1 个答案:

答案 0 :(得分:1)

您可以检查功能是否已定义:

var FileManager = {
    LoadRequiredFiles: function (config) {
        config = config || {};
        this.OnLoading = config.onLoadingCallback;
        this.OnCompleteCallback = config.onCompleteCallback;

        if(typeof this.OnLoading =='function') {
            this.OnLoading();
        }

        //Or use the shortcut:
        if(this.OnComplete) {
            this.OnComplete();
        }
    }
};

FileManager.LoadRequiredFiles(
    {
        onLoadingCallback: function() {
            alert('loading');
       }
    }
);