What is the best way to use an event in javascript? [closed]

2

Hello, I am starting in the world of programming in specific JavaScript, and I have a doubt, I am learning about events (onclick, onmouseover, etc).

And my doubt is that I have seen that many use events in different ways, we write them in their different forms in which they can be expressed so that they are executed. I want to know, based on your experience, which is the correct way to write them or, in your case, the most recommended, I give you 3 examples:

//Aquí escucho el evento poniendo todo junto
var clic = document.getElementById('out').addEventListener('mouseout',function(){
    alert('Saliste del elemento');
})

//Aquí hago uso directamente del evento sin usar el addEventListener
var btn = document.getElementById('btn').onmousover= function(){
    alert('Entraste en el elemento');
}

//Aquí desgloso todo, la variable que invoca a un id que se encuentra en el documento html, hago una función y después la invoco con el método addEventListener pero de forma separada a todo lo demás.
var texto = document.getElementById('texto');

function miTexto(){
    alert('estas en el texto');
}
texto.addEventListener('mouseover', miTexto);

What do you think is the most correct to use and most when writing hundreds of lines of code?

    
asked by CACZ 10.04.2017 в 16:32
source

3 answers

2

As you put in the comments, there is no way that is better because it will depend on the context or even the user, but I'll put the differences between one and another, which is the best will depend on different factors:

  • how many event handlers do you want to associate?
  • how many times will these event handlers be associated?
  • are you going to want to disassociate / reassociate those drivers later?
  • what browsers do you want to support? ...

Here is a description of each one:

AddEventListener (with an anonymous function)

var clic = document.getElementById('out').addEventListener('mouseout',function(){
    alert('Saliste del elemento');
})

The main advantage of this method is that will allow you to associate more than one action per event , that is, you can associate multiple functions with addEventListener and they will all be executed in the order in which who were associated.

An inconvenience comes when debugging ( debug ) the code if a failure occurs. If you have several anonymous functions associated with the event, in the error console you will only see that the error occurred in an unnamed function, but which one? You will need to go a little deeper in debugging to find the problem.

Another drawback (though minor) is that in older versions (and no longer supported) Internet Explorer addEventListener does not work and you should use attachEvent instead.

Example in which the two functions are executed, one of them fails but you do not see which one failed:

document.getElementById("btn").addEventListener("click", function() {
	console.log("funcion 1");
  funcionError();
});

document.getElementById("btn").addEventListener("click", function() {
	console.log("funcion 2");
});
<button id="btn">Mi botón</button>

AddEventListener (with a nominal function)

var texto = document.getElementById('texto');

function miTexto(){
    alert('estas en el texto');
}
texto.addEventListener('mouseover', miTexto);

This method is equivalent to the previous one. It is the same, only that instead of using an anonymous function, you are using a "normal" function that has a name and that you pass as a parameter to addEventListener .

An advantage over the previous one is that in case of error, in the error console you will see the name of the function where there are problems, which will facilitate the work of debugging.

Example in which the two functions are executed, one of them fails and you can see which one failed:

function miFuncion1() {
	console.log("funcion 1");
  funcionError();
}

function miFuncion2() {
	console.log("funcion 2");
}

document.getElementById("btn").addEventListener("click", miFuncion1);
document.getElementById("btn").addEventListener("click", miFuncion2);
<button id="btn">Mi botón</button>

Event attribute

var btn = document.getElementById('btn').onmousover= function(){
    alert('Entraste en el elemento');
}

This method is more restrictive than the others, really what you are doing is assigning the event handler attribute ( onclick , onmouseover ...) of the label, which leaves a big inconvenience: it can only have a value That is, if you assign more than one function, only the last one will be executed.

Another drawback of using this method (especially if you do inline directly on the label) is that you can block the function for security reasons. For example, if you develop web applications with Cordova, this method will give you problems.

Example in which only the second function that is associated will be executed:

document.getElementById("btn").onclick = function() {
  console.log("funcion 1");
}

document.getElementById("btn").onclick = function() {
  console.log("funcion 2");
}
<button id="btn">Mi botón</button>

That said, the method you use (you could also use jQuery or another JS library) will depend on the situation and the objective you want to achieve.

    
answered by 10.04.2017 в 18:04
0

The question is very personal, so I answer from my own point of view:

  

If you can place the event directly to the element it will be better, since you do not include additional processing.

Let me explain: Assuming you have a button ( button or input ) and you want to associate an event, simply put it in the description of it:

<button id="btn" onclick="miFuncion()">Presiona!</button>

<script>
    miFuncion = function(){
        alert("¡Hola mundo!");
    }
</script>

This I do because I've had to deal with functions that are never called by x or and why I programmatically , so I prefer it that way.

On the other hand, you could even ask which notation is better, if doing it by miFuncion = function(){...} or function miFuncion(){...} ; the language is very extensive like any other, there are many personal criteria that define how each one will write their code and therefore you only have to read about the language, understand the programming, make your own experiments and find the way that best suits you.

    
answered by 10.04.2017 в 18:08
-1

Since you are starting, I recommend you use jQuery , write less and develop more! ..;) )

Here is an example of how to handle events with jQuery :

$(document).ready(function () {
 $("#Event").on("mouseover",function () {
  console.log("on mouse Over!!");
 });
 $("#Event").on("mouseout",function () {
  console.log("on mouse Out!!");
 });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Event">Hello!</div>
    
answered by 10.04.2017 в 17:20