Search code examples
javascriptjqueryiife

How to reference a parent JavaScript function in a nested IIFE module?


Take the following code below... In the setTimeout anonymous function, what is the correct way to reference the alert.hide() method? Is it correct to just write out the whole call as admin.alert.hide();? or Is there a better way to reference admin without having to call it directly?

var admin = (function(jQuery, window, document, undefined) {
    return {
        loader : (function(admin) {
            var fade = 75;
            var loader = '#loader';
            return {
                show : function () {
                    jQuery(loader).stop().fadeIn(fade);
                },
                hide : function() {
                    jQuery(loader).stop().fadeOut(fade);
                }
            }
        })(),
        alert : (function() {
            var timeout;
            var fade = 500;
            var milliseconds = 1000;
            var alert = '#alert';
            return {
                timeout : timeout,
                show : function(message) {
                    jQuery(alert).find('p').text(message);
                    jQuery(alert).stop().fadeIn(fade);
                    clearTimeout(this.timeout);
                    this.timeout = setTimeout(function() {  }, milliseconds);
                },
                hide : function() {
                    jQuery(alert).stop().fadeOut(fade);
                }
            }
        })()
    }
})(jQuery, window, document);

Solution

  • You could do the following:

    return 
    {
        timeout : timeout,
        show : function(message) 
        {
            jQuery(alert).find('p').text(message);
            jQuery(alert).stop().fadeIn(fade);
            clearTimeout(this.timeout);
            this.timeout = setTimeout((function() { this.hide(); }).bind(this), milliseconds);
        },
        hide : function() 
        {
            jQuery(alert).stop().fadeOut(fade);
        }
    }