Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare function and call it on jquery event binding

I saw, some days ago, an alternate way to use functions on jQuery event bindings. It consists on: first declare the function, and then call it on the binding, like as follows. I think the code remains better organized.

//Função para capturar e passar os elementos para a função de apply.
function invokeSequentialFade(){
    //code...
};

//Função para Instanciar o carousel de acordo com o dispositivo.
function invokeCarousel(){
    //code...
};

//Função para instanciar o scrollfade (elementos surgirem no scroll).
function invokeScrollFade(){
    //code..
};

//Fixando a navbar no topo, caso o usuário não esteja na Home.
function manipulateFixedNavbar(){
    //code...
};

/************ END - Declaração de funções ***********/

$(window).on("resize",invokeCarousel);
$(window).on("resize",manipulateFixedNavbar);
$(window).on("resize",invokeSequentialFade);
$(document).on("scroll",invokeScrollFade);

I haven't found any article explaining if this is a good practice.

My doubt is: can this wreak havoc? I also have AJAX loaded content in my page, so I don't know if this method does affect the application in any sort of situation.

like image 990
undefined is our god Avatar asked Dec 18 '15 18:12

undefined is our god


1 Answers

The only way this could disturb existing code is if you had local variables with the same name as the functions.

The above is very unlikely, so go ahead and use whatever makes the code most readable. If your handler is just a few lines, I usually just use the inline anonymous function. For bigger handlers, it helps me to see the flow of the code without having to dig through/skip handlers

like image 156
Juan Mendes Avatar answered Sep 28 '22 02:09

Juan Mendes