apelliciari apelliciari - 1 month ago 6
jQuery Question

Jquery: i have a function $.fn.my_function with other functions inside, how can i call them?

Suppose i have this ($ = jquery):

$.fn.my_function = function() {
function foo()
{
//do something
};

function bar()
{
//do something other
};

}


I lauch this with
$('.my_class').my_function();


Now, i need to call foo and bar on callback to certain events.

How can i call them?

TM. TM.
Answer

You'll have to expose them to the "outside world" somehow. Currently, they are only visible within my_function so you won't be able to call them from anywhere else.

The most naive way to fix this would be something like:

var foo;
var bar;
$.fn.my_function = function() {
    foo = function() {
       //stuff
    };
    bar = function() {
       //stuff
    };
};

The same concept could be applied to place references to them anywhere that makes sense for your usage.

Comments