Class as an Event Observer
I want to do something like this...
var Color = Class.create({
initialize: function() {
this._color = "white";
this.observe("evt: colorChanged", this.colorChanged.bind(this));
},
changeColor: function(color) {
this._color = color;
this.fire("evt: colorCh开发者_运维百科anged");
},
colorChanged: function(event) {
alert("You change my color!");
}
});
var a = new Color().changeColor("blue");
Why the colorChange
custom event will never be dispatched and I need to use, instead of this
, a DOM element like document.observe
?
In my code I'd like to know which class dispatches the event using event.target
and I can't if I must use document
or some other DOM element. :(
I've been working in Actionscript 3 and that's the methodology I learned to work with custom events in classes. What about Javascript?
This should work:
var Color = Class.create({
initialize: function() {
this._color = "white";
Event.observe(document, "evt: colorChanged", this.colorChanged.bind(this));
},
changeColor: function(color) {
this._color = color;
Event.fire(document, "evt: colorChanged", this, false);
},
colorChanged: function(event) {
alert("You change my color!");
}
});
var a = new Color().changeColor("blue");
精彩评论