可以在jQuery中使用“窗口"作为事件总线吗? [英] Is it OK to use 'window' as an event bus in jQuery?

查看:93
本文介绍了可以在jQuery中使用“窗口"作为事件总线吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究jQuery的Events方法,并使用以下代码构建了一个简单的事件总线:

$(window).on('test:event', function (event, data) {
    console.log('Saw a test event: event=%o, data=%o', event, data);
});

$(window).trigger('test:event', {test_data: 'foo'});

我的问题是,使用窗口"管理事件是否存在任何问题?

解决方案

是的,这是在DOM冒泡上下文之外使用自定义jQuery事件的强大方法.但这也可以通过使用空对象{}而不是窗口来更有效地完成(无需查询DOM,因为它性能昂贵且与我认为的要求无关).

Ben Alman 写了很棒的 jQuery插件用于以避开一些不相关的jQuery事件元素的方式管理事件,同时使用相同的原理来实现轻量级的 解决方案

Yes, this is a great way of using the power of custom jQuery events outside of the context of DOM bubbling. But it can also be done more efficiently (without querying the DOM, since that's performance-expensive and unrelated to the requirements I assume), by using an empty object {} instead of the window.

Ben Alman wrote a great jQuery plugin for managing events in this way that eschews some of the irrelevant jQuery events elements while using the same principle to achieve a lightweight Publish / Subscribe pattern (listen for and trigger events defined by strings, with optional extra arbitrary data passed between).

这篇关于可以在jQuery中使用“窗口"作为事件总线吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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