Monday, June 24, 2013

Calling a jQuery plugin's private function in setInterval()

(function($){
    $.fn.something = function(options)
    {
        var opts = $.extend({}, $.fn.something.defaults, options);
        return this.each(function()
        {
            var $this = $(this);
            $this.click(function(){
                startSomething($this);
            });
        });
        // Private function
        function startSomething($this)
        {
            // $this is defined
            setInterval(function(){
                doSomething($this);
            }, 1000);
        };
        // Another private function
        function doSomething($this)
        {
            // $this is undefined
            $this.toggle();
        };
    };
    $.fn.something.defaults = {
        my_option: 'value'
    };
})(jQuery);

$('#test').something();

No comments:

Post a Comment