Skip to content

Instantly share code, notes, and snippets.

@anutron
Created December 22, 2010 19:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anutron/751974 to your computer and use it in GitHub Desktop.
Save anutron/751974 to your computer and use it in GitHub Desktop.
PassEvents.js
/*
---
description: Allows you to pass through events in Class instances.
provides: [Events.Relay]
requires:
- Core/Events
script: Events.Relay.js
...
Example usage:
var StreetFighter = new Class({
Implements: Events,
fight: function(){
if (Number.random(0,1)) this.fireEvent('win');
else this.fireEvent('lose');
}
});
var Player = new Class({
Implements: Events.Relay,
initialize: function(){
this.game = new StreetFighter();
this.inheritEvents({
win: this.game,
lose: this.game
});
}
});
var valerio = new Player();
valerio.addEvents({
win: function(){
alert('Valerio wins!');
},
lose: function(){
//not used; not possible to be invoked
}
});
Note:
Why do you need both relayEvent and inheritEvent? Because you may want to pass along events
from a class you don't control. Consider Fx in Core. If I'm writing something with an effect
and I want to fire onComplete when the Fx is done, I shouldn't have to alter the Fx class to
do so.
*/
Events.Relay = new Class({
relayEvent: function(name, target){
return this.addEvent(name, function(){
target.fireEvent(name, arguments);
});
},
relayEvents: function(obj){
for (name in obj){
this.relayEvent(name, obj[name]);
}
},
inheritEvent: function(name, target){
return target.addEvent(name, function(){
this.fireEvent(name, arguments);
}.bind(this));
},
inheritEvents: function(obj){
for (name in obj){
this.inheritEvent(name, obj[name]);
}
}
});
@appden
Copy link

appden commented Dec 23, 2010

Global variable alert!

@anutron
Copy link
Author

anutron commented Dec 23, 2010

got it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment