devric
devric

Reputation: 3665

jQuery, undefined function if used in a different function

I'm writing a jQuery plugin, which similar to this,

$(this).each(function(){
    $el = $(this).find('.el')
    $el.click(function(){
       test();
    });
    function test() {
       console.log('test init');
    }
});

This works fine when $el is clicked

but when i use the test() outside of $el.click like this

$(this).each(function(){
    $el = $(this).find('.el')
    test();
    function test() {
       console.log('test init');
    }
});

I get type error undefined is not a function

PS: I'm coding in coffee, syntax/spelling isn't an issue here

Upvotes: 1

Views: 350

Answers (1)

Joseph
Joseph

Reputation: 119847

if your test() needs to execute immediately, then do this:

$(this).each(function(){
    $el = $(this).find('.el')

    (function test() {
       console.log('test init');
    }());                          //the "()" at the end executes the function
});

but test() won't be available from the outside world this way. it's somewhat "enclosed". if you need test to execute immediately and still be callable by others, do this:

$(this).each(function(){
    $el = $(this).find('.el')

    var test = (function testFunc() {
       console.log('test init');
       return testFunc;                //return itself to the variable "test"
    }());                              //execute
});

Upvotes: 2

Related Questions