我应该在哪里绑定jQuery中的全局事件 [英] Where should I bind a global event in jQuery

查看:342
本文介绍了我应该在哪里绑定jQuery中的全局事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否要创建一个自定义的全局事件侦听器,以在其中绑定该事件.我应该使用哪一个?

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');

$(document).trigger('someEvent');

$('body').trigger('someEvent');

例如,在一个站点上有主页,关于我们,新闻和其他一些页面.每个页面都有其自己的javascript文件,即home.js,about-us.js ..等.还有一个通用的javascript文件main.js,该文件可提供整个网站的所有核心或通用功能.

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.

现在我想通过像这样在main.js中触发自定义事件来集中所有$(document).ready()和$(window).resize()函数

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');
});

$(window).resize(function(){
$(window).trigger('windowReszie');
}); 

因此,在所有的javascript文件中,它们只需要一个eventListener来进行相应的事件,而不是在每个文件中重复这些ready()或resize()函数.

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?

推荐答案

我认为您可以使用发布/订阅模式,该模式是基于事件的思考方式,但是 事件"不与特定对象相关联..

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.

您的代码将如下所示

main.js

$(document).ready(function(){
    $.publish('documentReady');
});

$(window).resize(function(){
    $.publish('resize');
}); 

然后,在其他.js文件中,您只需订阅:

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)

这篇关于我应该在哪里绑定jQuery中的全局事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆