Search code examples
javascriptjqueryorganization

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.


Solution

  • No, this won't harm any of the functionality and will help you maintain code efficiently. Note: wrap all off your code with self executive function which help you to prevent your code distribution from outside world.

    Advantage of using this structure: 1)Readable 2)methods can be reused 3)easy to maintain