Event handler context

Avrei potuto ottimizzare il codice del mio Style switcher step 2 in questo modo:

 $(document).ready(function() {
$('#switcher-normal').bind('click', function() {
$('body').removeClass('narrow').removeClass('large');
});
$('#switcher-narrow').bind('click', function() {
$('body').addClass('narrow').removeClass('large');
});
$('#switcher-large').bind('click', function() {
$('body').removeClass('narrow').addClass('large');
});
$('#switcher .button').bind('click', function() {
$('#switcher .button').removeClass('selected');
$(this).addClass('selected');
});
});

Sto mettendo a frutto tre funzionalità di JQuery

Ma posso fare ancora di meglio:

$(document).ready(function() {
$('#switcher .button').bind('click', function() {
$('body').removeClass();
if (this.id == 'switcher-narrow') {
$('body').addClass('narrow');
}
else if (this.id == 'switcher-large') {
$('body').addClass('large');
}
$('#switcher .button').removeClass('selected');
$(this).addClass('selected');
});
});

Cfr. Styler explorer step 3

Inoltre è possibile usare una sintassi 'shorthand' al metodo bind() si sostituisce il gestore d'evento click():

$(document).ready(function() {
$('#switcher .button').click(function() {
$('body').removeClass();
if (this.id == 'switcher-narrow') {
$('body').addClass('narrow');
}
else if (this.id == 'switcher-large') {
$('body').addClass('large');
}
$('#switcher .button').removeClass('selected');
$(this).addClass('selected');
});
});