Djave
Djave

Reputation: 9329

JavaScript self invoking function closure not working correctly

Disclaimer: I'm trying to use closures as I have been told they are a good practise (and I understand that – not having variables get used in other functions etc) but I don't 100% understand what I'm doing! 99% of the time they work great.

I have the following function:

(function(){
    $("#job-titles-list a").click(function(e){
        e.preventDefault();
        return false;
    });
});

But when I click any of the links, I am taken to their href. If i change the function to:

// (function(){
    $("#job-titles-list a").click(function(e){
        e.preventDefault();
        return false;
    });
// });

My question is how can I make the closure work / should I not be using closures to do what I'm doing?

(I know I don't need both return false and e.preventDefault() but I was trying a couple of things when it wasn't working)

Upvotes: 0

Views: 144

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

You defined the enclosure, but have not called it:

(function(){
    $("#job-titles-list a").click(function(e){
        e.preventDefault();
        return false;
    });
})(); // < -- Note the () here.

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382150

You define a function expression but you don't call it. Add parenthesis :

(function(){
    $("#job-titles-list a").click(function(e){
        e.preventDefault();
        return false;
    });
})();

Note that if you don't have more code inside the IIFE, it's totally useless as you're not adding any variable.

Upvotes: 3

Related Questions