类的唯一 JQuery 事件
我正在尝试创建一个可以发送独特 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
“独特”是什么意思?如果您需要一个自定义事件类,那么您需要扩展 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.