The following code is redundant---the same anonymous function appears three times.
How do I refactor it?
$(".operation").resizable({
crea开发者_如何学编程te: 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)
},
})
You can use a local variable:
(function() {
var f = function(event,ui) {
var width = $(".operation").width()
$("#width span.text").text(width)
}
$(".operation").resizable({
create: f,
resize: f,
stop: f,
})
})()
the upside is that you do not pollute the global namespace (global object).
You can define a global function if you don't mind.
I would declare the function:
function setWidth(event, ui) {
var width = $(".operation").width();
$("#width span.text").text(width);
}
$(".operation").resizable({
create: setWidth,
resize: setWidth,
stop: setWidth,
});
declare a new function
function xxx(event, ui) {
var width = $(".operation").width();
$("#width span.text").text(width);
}
then set it as the callback:
$(".operation").resizable({
create: xxx,
resize: xxx,
stop: xxx
});
精彩评论