类的唯一 JQuery 事件

发布于 2024-12-19 00:15:33 字数 526 浏览 0 评论 0原文

我正在尝试创建一个可以发送独特 jQuery 事件的类。示例:

function Bomb(id) {
    this.evnt = $.Event("BOOM!_" + id);
    this.detonate = function() {
        $(document).trigger(evnt);
    };
}
var firecracker = new Bomb();
var nuclearbomb = new Bomb();

$(document).bind(firecracker.evnt.type, function(){
    // It's the fourth of july!!!
});

$(document).bind(nuclearbomb.evnt.type, function(){
    // We're dead
});

firecracker.detonate();
nuclearbomb.detonate();

如何在 Bomb 类中创建唯一事件,而无需传入 ID 来为该类创建唯一事件字符串?

I am trying to create a class that can send a unique jQuery event. Example:

function Bomb(id) {
    this.evnt = $.Event("BOOM!_" + id);
    this.detonate = function() {
        $(document).trigger(evnt);
    };
}
var firecracker = new Bomb();
var nuclearbomb = new Bomb();

$(document).bind(firecracker.evnt.type, function(){
    // It's the fourth of july!!!
});

$(document).bind(nuclearbomb.evnt.type, function(){
    // We're dead
});

firecracker.detonate();
nuclearbomb.detonate();

How can I create a unique event within the Bomb class without having to pass in an ID to create a unique event string for the class?

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梅窗月明清似水 2024-12-26 00:15:33

“独特”是什么意思?如果您需要一个自定义事件类,那么您需要扩展 jQuery 的类,或者根据规范提供您自己的事件接口实现以及周围的所有内容 (记录对象模型事件)。请在此处查看一些想法:Dean Edwards 博客

我还应该提到的一件事是,您对所有事件使用相同的事件目标。在大多数情况下,在同一对象上调度的相同类型和名称的事件意味着相同的情况。因此,如果您需要以不同的方式处理事件,则需要按名称(如您所做的那样)或按目标($(firecracker).bind('ondetonate', function () { ... }))。

抱歉,如果这不是具体的,但我只是想提供一个总体思路,即如何解决这个问题。

What do you mean under 'unique'? If you need a custom class for event, then you'll need to extend jQuery's one or to provide your own implementation of Event interface and everything around according to the spec (Document Object Model Events). See some ideas here: Dean Edwards Blog.

One more thing, I should mention, is, that you are using the same event target for all events. In most cases events of same type and name dispatched on the same object mean the same case. So if you need to process events differently, you'll need to differ them by name (as you've done) or by target ($(firecracker).bind('ondetonate', function () { ... })).

Sorry, if this was not specific, but I've just wanted to provide a general idea, how this could be solved.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文