Created
December 22, 2010 19:35
-
-
Save anutron/751974 to your computer and use it in GitHub Desktop.
PassEvents.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
--- | |
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]); | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Global variable alert!