2011-03-18 3 views
1

Le code suivant est redondant --- la même fonction anonyme apparaît trois fois.En Javascript, comment puis-je refactoriser des fonctions anonymes répétées?

Comment le refactoriser?

$(".operation").resizable({ 
create: function(event, ui) { 
    var width = $(".operation").width() 
    $("#width span.text").text(width) 
}, 
resize: function(event, ui) { 
    var width = $(".operation").width() 
    $("#width span.text").text(width) 
}, 
stop: function(event, ui) { 
    var width = $(".operation").width() 
    $("#width span.text").text(width) 
}, 
}) 

Répondre

3

Je déclare la fonction:

function setWidth(event, ui) { 
    var width = $(".operation").width(); 
    $("#width span.text").text(width); 
} 

$(".operation").resizable({ 
    create: setWidth, 
    resize: setWidth, 
    stop: setWidth, 
}); 
4

Vous pouvez utiliser une variable locale:

 (function() { 
     var f = function(event,ui) { 
      var width = $(".operation").width() 
      $("#width span.text").text(width) 
     } 
     $(".operation").resizable({ 
     create: f, 
     resize: f, 
     stop: f, 
     }) 
    })() 

la hausse est que vous ne pollue pas l'espace de noms global (objet global).

Vous pouvez définir une fonction globale si cela ne vous dérange pas.

+0

+1, mais en supposant qu'il est déjà en cours d'exécution à l'intérieur d'une fermeture/fonction, la fermeture supplémentaire n'est pas nécessaire. –

1

Déclarez une nouvelle fonction

function xxx(event, ui) { 
    var width = $(".operation").width(); 
    $("#width span.text").text(width); 
} 

puis définissez comme le rappel:

$(".operation").resizable({ 
    create: xxx, 
    resize: xxx, 
    stop: xxx 
}); 
+0

Vous voyez que je ne suis pas un fan de ce nom en raison de l'absence de code lié p0rn. – ChaosPandion

+0

créer, redimensionner et arrêter ne sont pas liés pr0n ?? – Spikolynn

Questions connexes