使用prototype.js 的类实例上的事件
使用 Mootools,您可以将事件监听器添加到类的实例中。 像这样:
var Widget = new Class({
Implements: Events,
initialize: function(element){
// ...
},
complete: function(){
this.fireEvent('complete');
}
});
var myWidget = new Widget();
myWidget.addEvent('complete', myFunction);
是否有可能在原型中而不是文档中的实例链接上添加事件? (Event.observe(document, "evt: eventType", eventHandler);)
With Mootools, you can add a eventListener to an instance of a class.
Like this:
var Widget = new Class({
Implements: Events,
initialize: function(element){
// ...
},
complete: function(){
this.fireEvent('complete');
}
});
var myWidget = new Widget();
myWidget.addEvent('complete', myFunction);
Is there any posibility to add events on instances link that in prototype and NOT on the document? (Event.observe(document, "evt: eventType", eventHandler);)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Prototype 的自定义事件与 DOM 事件相关,因此如果不以某种方式使用 DOM,就无法在类或实例上触发事件。也就是说,您可以使用 Prototype 的自定义事件将自定义事件添加到您的类中,而无需太多额外的工作。
几年前,Tobie Langel 分享了一种向 Prototype 类添加自定义事件的方法;这种方法的缺点是这些事件是在类级别触发和观察的,这意味着由一个实例触发的事件将被观察该类的任何实例的所有侦听器拾取。
我对 Tobie 的方法做了一些简单的修改,允许单独观察实例。这里的技巧是使用 Class.create 周围的闭包为类的每个实例创建一个私有事件命名空间。每次创建类的新实例时,计数器都会递增。
Prototype's custom events are tied DOM events so there's no way to fire events on classes or instances without using the DOM in some way. That said you can use Prototype's custom events to add custom events to your classes without too much extra work.
A few years ago Tobie Langel shared a way of adding custom events to Prototype classes; the drawback with this approach is that these events are fired and observed at the class level, meaning events fired by one instance with be picked up all listeners observing any instance of that class.
I made a few simple modifications to Tobie's approach, which allow instances to be observed individually. The trick here is using a closure around
Class.create
to create a private event namespace for each instance of the class. The counter is incremented each time a new instance of the class is created.