Shawn Mclean
Shawn Mclean

Reputation: 57469

Javascript optional parameters for callbacks

I want to do something like $.ajax() success and error callbacks.

This is what I have so far:

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');
       }
});

How do I fix this up properly? I'm using FileManager as my namespace.

Upvotes: 1

Views: 225

Answers (1)

The Scrum Meister
The Scrum Meister

Reputation: 30111

You can check if the functions are defined:

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');
       }
    }
);

Upvotes: 1

Related Questions