Is it possible to declare a var in jquery.live() (as well as .delegate() & .on()) which can be used in all functions?
Example:
$("#s4-leftpanel-content ul.root > li.static > a").live({
click: function (event) {
var hasChildren = $(this).parent('li').children('ul').length > 0;
if (hasChildren) {
event.preventDefault();
$("#s4-leftpanel-content ul.root li.static > ul.static").hide();
$(this).parent('li').children('ul').toggle();
}
},
mouseover: function () {
$(this).css('background-color', 'green');
},
mouseout: function () {
$(this).css('background-color', '');
}
});
Lets say I want to use the bool var hasChildren in the mouseover and mouseout function as well, do I then have to declare that var again in these 2 functions or is there a way in which I can just declare it globally within this current object?
Variables declared with
varare always local to the context, in this case the event handler.You have three possibilities:
Create the variable in a scope reachable by all event handlers
For example:
The self-invoking function creates a new scope.
hasChildrenis only accessible by the event handlers and does not leak into global scope.Use
.data()[docs].data()allows you to attach arbitrary data to a DOM element.Update:
As @pimvdb noted, as
mouseoveris always triggered beforeclick, you can just assign the value in yourmouseoverevent handler and then access it in the other handlers either by$(this).data('hasChildren')or justhasChildren, depending on which way you choose (changed the code to reflect this).Factor out the computation
As the determination whether the element has children or not only depends on the element itself, you could also factor out this line of code into an extra function and call it in every event handler:
Of course this comes with the cost of repeating the same computation, but you are at least not repeating code.