简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM