Declare a function and call it when binding a jquery event

A few days ago, I saw an alternative way to use functions in jQuery event bindings. It consists of: first declare a function, and then call it a binding, as shown below. I think the code remains more 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 did not find an article explaining if this is good practice.

I doubt: could it be harmful? I also have downloaded AJAX content on my page, so I don’t know if this method affects the application in any situation.

+5
source share
2 answers

No, this will not harm any functionality and help you maintain code efficiently. Note: wrap your code with its own function that helps you prevent code from spreading from the outside world.

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

+1
source

The only way to break existing code is if you have local variables with the same name as the functions.

The foregoing is highly unlikely, so go ahead and use whatever makes the code the most readable. If your handler is only a few lines long, I usually use the built-in anonymous function. For larger handlers, this helps me see the code flow without having to scroll / skip handlers

+4
source

Source: https://habr.com/ru/post/1238661/


All Articles