Search code examples
javascriptjqueryfunctioniife

How to make an Object method an IIFE?


I've been trying to make an object method an iife, but i've had no luck at all. Is it possible? We are storing all of our functions as methods in an attempt to keep them organised.

I have chosen ONE object & one method to illustrate what I am trying to do, though we have many more.

I'd like to IIFe-fy them because as soon as they initially fire, they have done their job and aren't needed again, with that in mind along with how many methods we will have, to me it makes to iife-fy them.

My code is:

let trans = {
    bind_toggle: function(){
        if ($('.tw-o').length != 0) {
            // window open, add toggle
            $('.tw-h').click(function(e){
                $('.tw-b').toggle(599);
            });
        }
    } 
}

I'd like trans.bind_toggle to be invoked without having to call it myself... an IIFE, but i've not been able to pull it off. I've tried:

let trans = {
    bind_toggle: (function(){
        if ($('.tw-o').length != 0) {
            // window open, add toggle
            $('.tw-h').click(function(e){
                $('.tw-b').toggle(599);
            })();
        }
    } 
}

The above returns

Uncaught TypeError: trans.bind_toggle is not a function

Is it possible to use an IIFE in an object? if so, how would I do it?

Thank you :)


Solution

  • Instead storing one-timer-functions in an object, I'd suggest you to wrap all the code in an IIFE, and then declaring the one-timers in the scope of that function, or make them IIFEs like in the example below. That way they will be decently garbage collected after the IIFE has run. Something like this:

    (function () {
        (function () {
            // Logig for bind_toggle
        }());
        // All the rest of your code
    }());
    

    Having all the code in an IIFE you can avoid to declare most of global variables too. If a global is really needed, you can define it as a property of window, like window.someGlobal = 1.