I am trying to figure out how I can reuse a variable within a function, right now I have to put it in each scope for it to work.
Say I have an jQuery Event handler:
$('.button').on('click', function() {
var btn = $(this).data('button');
$(this).addClass(btn+'-activate');
}).on('mouseup', function() {
var btn = $(this).data('button');
$(this).removeClass( btn+'-activate');
}).on('mouseleave', function() {
var btn = $(this).data('button');
$(this).removeClass( btn+'-activate');
}
How can I reuse the variable 'btn'? When I put it in the parent scope, it doesn't recognize $(this) anymore
It is better to reuse variables in terms of memory. But be careful you don't need the value in a variable before reusing it. Other than that, you shouldn't use always the variable. It is important to keep a clean and readable code.
Do not use the same variable name in two scopes where one scope is contained in another. For example, No other variable should share the name of a global variable if the other variable is in a subscope of the global variable.
No it's not possible to redefine a variable using a different type in the same scope.
As a general principle, do not reuse variables to point to different objects. This is extremely error prone. In your specific example, since you are recreating the connection object in each call to SqlThingyMethod there is likely no benefit to storing it in a field. Use a local variable.
The other answers have a bit of redundancy in them. Here is how I usually handle events that are related and have common variables:
$('.button').on('click mouseup mouseleave', function(event) {
var btn = $(this).data('button');
switch(event.type) {
case 'click': {
$(this).addClass(btn+'-activate');
break;
}
case 'mouseup':
case 'mouseout':
case 'mouseleave': {
$(this).removeClass(btn+'-activate');
break;
}
}
});
Listen to multiple events and use a switch statement to determine which event was called.
You can just iterate over the buttons, set the variable for each one and then use the variable inside the event handlers.
$('.button').each(function() {
var btn = $(this).data('button');
$(this).on('click', function() {
$(this).addClass(btn+'-activate');
}).on('mouseup mouseleave', function() {
$(this).removeClass( btn+'-activate');
});
});
But of course this is not exactly the same as your code. Here we are setting the value of btn
at the time the handlers are attached while, in the code of the question, btn
is set at the time the handlers are called. Therefore this is only a valid alternative if the value of .data('button')
is not meant to change.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With