Crystal
Crystal

Reputation: 29458

passing callback function and parameters to a javascript function

I'm pretty new to JS. I have a helper class that does some of the common fetching to the server. Currently, one of those functions would look like this:

getAvailablePlatforms: function (platform) {
            var self = this;
            if (_.isUndefined(platform) || platform == '') {
                platform = "crystalproject";
            }

            $.ajax({
                url: '/api/platform/' + platform,
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    console.log("Got data");
                    self.platforms = data;
                    self.eventAggregator.trigger('getplatforms');  
                },
            });
        }

So what I wanted to try to make this more flexible was to pass in the callback function. So I tried this:

getAvailablePlatforms: function (platform, callback) {
            var self = this;
            if (_.isUndefined(platform) || platform == '') {
                platform = "crystalproject";
            }

            $.ajax({
                url: '/api/platform/' + platform,
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    console.log("Got data");
                    self.platforms = data;
                    self.eventAggregator.trigger('getplatforms');  
                    if (callback && typeof(callback) === "function") {
                        callback(data);
                    }
                },
            });
        }

How I want to call it though, is like this:

var helper = new Helper();
helper.getAvailablePlatforms('', this.populatePlatforms(???????));

I want my callback function to use the data that it received in the callback. How can I achieve that? Thanks in advanced!

Upvotes: 1

Views: 233

Answers (1)

PSL
PSL

Reputation: 123739

You would just pass in the function reference. You don't want to call the function by ending it will () while passing the callback, instead of the function reference the call back would end up being the result of the function (if nothing is returned it will be undefined). populatePlatforms inside getAvailablePlatforms: function (platform, callback) {

So you would want to go with:

helper.getAvailablePlatforms('', this.populatePlatforms);

For passing in the context use ecmascript5 function.prototype.bind function.

helper.getAvailablePlatforms('', this.populatePlatforms.bind(this));

Upvotes: 3

Related Questions