Search code examples
javascriptjqueryiife

Pass dynamic params to IIFE


I've got this issue with passing a variable to an IFFE. did some reading, still didn't figure it out. would really appreciate some guidance here.

  • i have a click event handler function that gets a certain ID from the DOM when clicked.
  • i need to pass that ID to an IIFE
  • that IFFE needs to either add/remove that ID from an array, depending if it's already there or not.

This is what I got:

Event:

$(document).on('click', 'input[type="checkbox"]', check);

Click Handler:

function check() {
    var id = $(this).closest('ul').attr('data-id');
    return id;
}

IIFE:

var checkID = (function (val) {

    var arr = [];

    return function () {

        var i = arr.indexOf(val);

        if (i === -1) {
            arr.push(val);
        } else {

            arr.splice(i, 1);
        }
        return arr;
    }

})(id);

right now i'm getting the ID, but returning it to nowhere.

in my IIFE, i did pass an id variable, but it's undefined.

so, how do I pass the ID variable im getting from check() to checkID IIFE?

other solutions are also welcome.

Thanks


Solution

  • I think you need to do things sort of the other way around. Your check function would return a function used by the event handler, but it would also take a callback to be called after the click handler has run, passing your array.

    The check function would look like a mash-up of both your functions:

    function check(callback){
      var arr = [];
      return function(){
        var id = $(this).closest('ul').attr('data-id');
        var i = arr.indexOf(id);
    
        if (i === -1) {
            arr.push(id);
        } else {
    
            arr.splice(i, 1);
        }
        callback(arr);
      }
    }
    

    As you can see, it takes as a parameter a callback function, which will be called on each execution, passing the current array arr. For example, this is my test callback:

    function handler(arr){
     alert("Array has " + arr.length + " elements");
    }
    

    Finally, your event handler would look like this:

    $(document).on('click', 'input[type="checkbox"]', check(handler));
    

    Live example: https://jsfiddle.net/src282d6/