开发者

In Javascript, how can I refactor some repeated anonymous functions?

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
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜