Search code examples
javascriptjqueryfunctionloopsdynamic-function

How can I make dynamic functions?


I have 10 functions like these:

function instagram_ajax(){
    return ajaxRequest('search/instagramid', 'instagramid').then(
        function(res) {
            var imgStatus = res[1].length > 0 ? "checked_successfully.png" : "checked_noRes.png";
            $('.option_name_instagramid + td').html("<img src='img/" + imgStatus + "' />")

            optionsRes['instagramid'] = res[1];

        }, function(err){
            $('.option_name_instagramid + td').html("<img src='img/warning.png' />")
        }
    );
}

function googleplus_ajax(){
    return ajaxRequest('search/googleplusid', 'googleplusid').then(
        function(res) {
            var imgStatus = res[1].length > 0 ? "checked_successfully.png" : "checked_noRes.png";
            $('.option_name_googleplusid + td').html("<img src='img/" + imgStatus + "' />")

            optionsRes['googleplusid'] = res[1];

        }, function(err){
            $('.option_name_googleplusid + td').html("<img src='img/warning.png' />")
        }
    );
}

.
.
.

As you see, those functions are almost equivalent, just the difference is words instagram, googleplus. Also I have an array of all those names:

var parts = ['instagram', 'googleplus', 'linkedin', 'facebook', ...];

Now I want to know, is it possible to make those array dynamically? I mean by putting a variable-base function into a loop and use that array to make all those functions? Is such a thing possible?


Solution

  • make a wrappper function

    function ajax(str) {
      return function() {
        return ajaxRequest('search/'+str+'id', ''+str+'id').then(
            function(res) {
                var imgStatus = res[1].length > 0 ? "checked_successfully.png" : "checked_noRes.png";
                $('.option_name_'+str+'id + td').html("<img src='img/" + imgStatus + "' />")
    
                optionsRes[str+'id'] = res[1];
    
            }, function(err){
                $('.option_name_'+str+'id + td').html("<img src='img/warning.png' />")
            }
        );
      }
    }
    
    var instagram_ajax = ajax('instagram');
    var googleplus_ajax = ajax('googleplus');
    

    or for your case

    var parts = ['instagram', 'googleplus', 'linkedin', 'facebook'];
    
    var funcs = {};
    for (var i = 0; i < parts.length; i++)
      funcs[parts[i]] = ajax(parts[i]);
    
    // now u do
    funcs.instagram()