Reputation: 89
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);)
Upvotes: 3
Views: 707
Reputation: 142
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.
var Observable = Class.create({
fire : function(eventName, data){
document.fire(this._namespace + ':' + eventName, data);
},
observe : function(eventName, callback){
document.observe(this._namespace + ':' + eventName, callback);
},
stopObserving : function(eventName, callback) {
// Probably wise to also implement this...
}
});
var Widget = (function(){
var namespace = 'widget', counter = 0;
return Class.create(Observable, {
initialize : function(){
this._namespace = namespace + ':' + counter++;
},
complete : function(){
this.fire('complete');
}
});
}());
var myWidget = new Widget();
myWidget.observe('complete', function(e){
// Callback executed when 'complete' is fired on myWidget.
});
Upvotes: 1