Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a method inside a jquery function from global scope?

I am looking for a way to call a method inside a jquery function.

Example : in the above code, how can I call the method() method from global scope?

(function( $ ) {

    $.fn.test = function() {

        var method = function() {
            alert('test succeeded!');
        };

    }

})( jQuery );

I tried with the following code:

$(document).ready(function() {

    $(document).test.method(); // undefined

});

But this does not help.

Fiddle: http://jsfiddle.net/kB7mc/

like image 676
Alain Tiemblo Avatar asked Jun 02 '26 07:06

Alain Tiemblo


1 Answers

Your method is of local scope available inside the function test only, you cannot access it outside the scope. Instead you can do it this way. Also while calling it, remember to put method invocation () for test i.e $(document).test().method(); instead of $(document).test.method();

(function( $ ) {

    $.fn.test = function() {
         var method = function() {
            alert('test succeeded!');
        };

         return {method:method};
    }

})( jQuery );

$(document).ready(function() {
    $(document).test().method(); // undefined
});

Fiddle

Using Jquery Plugin pattern.

(function ($) {
    var methods = {

        method : function () {
            alert('test succeeded!');
            return this; //return element for chaining
        },
         method2 : function () {
            alert('test2 succeeded!');
             return this;
        }
    };

    $.fn.test = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist');
        }
    }

})(jQuery);

$(document).ready(function () {
    $(document).test('method'); 
    $(document).test('method2'); 

});

Fiddle

like image 59
PSL Avatar answered Jun 03 '26 21:06

PSL



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!