Reputation: 4753
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
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
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