Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 474
Uzi Avatar asked Dec 29 '25 18:12

Uzi


1 Answers

In your clickHandler

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

and change checkID to

var checkID = (function () {

    var arr = [];

    return function (val) {

        var i = arr.indexOf(val);

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

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

})();
like image 87
user5325596 Avatar answered Dec 31 '25 08:12

user5325596



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!