At the moment, I have this code:
(function() {
var lastSelectedIndex = -1;
function onSelTypeSelected() {
// #selType is a <select> tag
// var selType = document.getElementById("selType");
var selType = this;
// finished(onSuccess, onError)
loader.finished(function(data) {
lastSelectedIndex = selType.selectedIndex;
}, function(err) {
selType.selectedIndex = lastSelectedIndex;
});
}
})();
So lastSelectedIndex
is not in the global context, however I want to put it into inside eventListener()
's context.eventListener()
, so you can't access it in the outer anonymous function.
That's cleaner in my opinion and also faster (okay, a few nanoseconds) because of the scope chains hierarchy (Google Tech Talk: Speed Up Your JavaScript is a good introduction).
I thought of adding a property to the function (as I learnt here) but I don't have access to eventListener()
in the anonymous functions.
The next idea I had was to use HTML 5 data-*
attributes:
function onSelTypeSelected() {
// #selType is a <select> tag
// var selType = document.getElementById("selType");
var selType = this;
// finished accepts two arguments: onSuccess and onError
loader.finished(function(data) {
selType.setAttribute("data-lastIndex", selType.selectedIndex);
}, function(err) {
selType.selectedIndex = selType.getAttribute("data-lastIndex");
});
}
(The default value for data-lastIndex
will be set in the HTML Markup)
lastSelectedIndex
is already ineventListener
's context, because they are declared at the same scope. \$\endgroup\$ – delete me Jun 3 '12 at 22:49