9blue
9blue

Reputation: 4753

What's the elegant way of binding multiple elements with different event respectively using same event handler?

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

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>

Upvotes: 3

Views: 75

Answers (2)

user193130
user193130

Reputation: 8227

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

Building upon TheShellfishMeme's answer:

// 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

Upvotes: 0

Tim
Tim

Reputation: 2440

It's very simple actually.

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

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

Upvotes: 6

Related Questions