开发者

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

开发者 https://www.devze.com 2023-02-18 16:46 出处:网络
The following code is redundant---the same anonymous function appears three times. How do I refactor it?

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

精彩评论

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

关注公众号