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');
});
});
- $('body').removeClass(); --- la funzione removeClass() può essere usata senza parametri (rimuove tutte le classi).
- $('#switcher .button').bind('click', function() --- ho scritto un solo gestore d'evento per tutti e tre i bottoni sfruttando il chaining di JQuery ed i selettori CSS.
- (this.id == 'switcher-narrow') --- ho usato il context della funzione: this all'interno di un gestore non rappresenta un oggetto JQuery ma un elemento del DOM, quindi, ricavandone l'id, posso evitare ripetizioni.
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');
});
});