问题
I am wondering if I want to create a custom global event listener, where I should bind that event. Which one should I use?
$(window).trigger('someEvent');
or
$(document).trigger('someEvent');
or
$('body').trigger('someEvent');
For example, there is a site in which it has home, about-us, news and some other pages. Each pages has its own javascript file, i.e. home.js, about-us.js.. and so on. And there's one common javascript file, main.js, which serves all the core or common functions throughout the whole site.
Now I want to centralize all the $(document).ready() and $(window).resize() functions by triggering custom event in the main.js like this
$(document).ready(function(){
$(document).trigger('documentReady');
});
and
$(window).resize(function(){
$(window).trigger('windowReszie');
});
And so all in all the javascript files, they just need an eventListener for corresponding event, instead of repeating those ready() or resize() functions in every file.
But I am not sure if it's good to bind all those custom events into the same object. If yes, which object should I bind, window? document? body?
回答1:
I think that you could use a Publish/Subscribe pattern which is an event-based way of thinking, but the "events" aren't tied to a specific object.
Your code will looks like this
main.js
$(document).ready(function(){
$.publish('documentReady');
});
$(window).resize(function(){
$.publish('resize');
});
then, in the others .js you can simply subscribe:
$.subscribe('documentReady', function(){ alert('documentReady'); });
$.subscribe('resize', function(){ alert('resize'); });
The Publish/Subscribe pattern also allows you to create modular and reusable code, and plays an important role in creating better applications, loosely coupled, flexible, scalable and easy to test.
THIS is a small working example of that code (i used jquery-tiny-pubsub plugin for publish/subscribe methods, but you can use whatever you want)
回答2:
All of the above work but you should always try be as specific as you can to the component you are interacting with. Custom events don't need to be binded to a high level DOM elements as you are describing.
Example:
$('.slider').trigger('someEvent');
来源:https://stackoverflow.com/questions/37857036/where-should-i-bind-a-global-event-in-jquery