What I want to do is to sending data between two handlers.
element.onmousedown = function() {
data = precalculate();
}
element.onmouseup = function() {
dosomething(data);
}
if the data is a global variable it works. People says global variable is evil. But I don’t know how to do without it.
or I misunderstood “global variable”?
Just scope the variable if you don’t want/need it to be global:
EDIT: To clarify, the only way to create a new variable scope in javascript is in a function.
Any variable declared with
varinside a function is inaccessible to the outer scope.In the code above, I created an IIFE (immediately invoked function expression), which is simply a function that is invoked as soon as it is created, and I placed your
datavariable (along with the handler assignments) inside of it.Because the handlers were created in a scope that has access to the
datavariable, they retain their access to that variable.To give another example: