有基于事件的 jQuery 编程结构的示例吗?

发布于 2024-12-11 10:28:41 字数 1029 浏览 1 评论 0原文

我已经构建了一个程序,我认为该程序可以从使用 jQuery 事件(bind() 和 trigger())而不是典型的函数调用编程结构的转变中受益。例如,

//device changed
//(diffs holds key: {old_val: 'old value', new_val: 'new value'} pairs)
DEVICES.update(device, diffs)
DIAGRAM.update(device, diffs)
TABLES.update(DEVICES.$table, device, diffs)

/*
...
*/

//device changed - some other code location
DEVICES.update(device, diffs);
DIAGRAM.update(device, diffs);
TABLES.update(DEVICES.$table, device, diffs);

我可以写:

//DEVICES.update(), DIAGRAM.update, and TABLES.update have all been bound to
//DEVICES.$container's device_changed custom event (in their respective modules)

//device changed
//(diffs holds key: {old_val: 'old value', new_val: 'new value'} pairs)
DEVICES.$container.trigger('device_changed', [device, diffs]);

/*
...
*/

//device changed - some other code location
DEVICES.$container.trigger('device_changed', [device, diffs]);

我正在学习如何有效地使用bind()和trigger(),但大多数情况下只是边做边补。有没有关于如何使用 jQuery 遵循这种事件驱动风格来编程/构造代码的好例子?

I've built a program that I think could benefit from a shift toward using jQuery's events (bind() and trigger()) instead of the typical function-calling programming structure. For example, instead of:

//device changed
//(diffs holds key: {old_val: 'old value', new_val: 'new value'} pairs)
DEVICES.update(device, diffs)
DIAGRAM.update(device, diffs)
TABLES.update(DEVICES.$table, device, diffs)

/*
...
*/

//device changed - some other code location
DEVICES.update(device, diffs);
DIAGRAM.update(device, diffs);
TABLES.update(DEVICES.$table, device, diffs);

I could write:

//DEVICES.update(), DIAGRAM.update, and TABLES.update have all been bound to
//DEVICES.$container's device_changed custom event (in their respective modules)

//device changed
//(diffs holds key: {old_val: 'old value', new_val: 'new value'} pairs)
DEVICES.$container.trigger('device_changed', [device, diffs]);

/*
...
*/

//device changed - some other code location
DEVICES.$container.trigger('device_changed', [device, diffs]);

I'm learning how to use bind() and trigger() effectively, but mostly just making it up as I go along. Are there any good examples of how to program/structure code following this event-driven style with jQuery?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文