使用相同的事件处理程序分别使用不同的事件绑定多个元素的优雅方法是什么?

时间:2022-03-22 21:58:58

I have both $(document) and $(window), they are bound with 'ready' and 'resize' event respectively. They are sharing the same event handler.

我有$(document)和$(window),它们分别与'ready'和'resize'事件绑定。他们共享相同的事件处理程序。

Code:

$(window).on('resize', function () {    
     Shared code
});
$(document).ready(function () {
     Shared code
});

Instead of the style above, is there a conventional way of handling this to make the code clean and simple>

而不是上面的风格,是否有一种传统的处理方式,以使代码清洁和简单>

2 个解决方案

#1


6  

It's very simple actually.

实际上它非常简单。

var handler = function (event) {
    // Whatever you want to handle
};

$(window).on('resize', handler);
$(document).ready(handler);

#2


0  

Another option if you don't want to pollute global namespace is to use an immediately executed anonymous function.

如果您不想污染全局命名空间,另一个选项是使用立即执行的匿名函数。

Building upon TheShellfishMeme's answer:

以TheShellfishMeme的答案为基础:

// handler will not be defined at this point
(function() {
    var handler = function (event) {
        // Whatever you want to handle
    };

    $(window).on('resize', handler);
    $(document).ready(handler);
})();
// handler will not be defined at this point

#1


6  

It's very simple actually.

实际上它非常简单。

var handler = function (event) {
    // Whatever you want to handle
};

$(window).on('resize', handler);
$(document).ready(handler);

#2


0  

Another option if you don't want to pollute global namespace is to use an immediately executed anonymous function.

如果您不想污染全局命名空间,另一个选项是使用立即执行的匿名函数。

Building upon TheShellfishMeme's answer:

以TheShellfishMeme的答案为基础:

// handler will not be defined at this point
(function() {
    var handler = function (event) {
        // Whatever you want to handle
    };

    $(window).on('resize', handler);
    $(document).ready(handler);
})();
// handler will not be defined at this point