Created
March 28, 2014 02:54
-
-
Save bttmly/9824253 to your computer and use it in GitHub Desktop.
Two ways of structuring Controls.js collection classes.
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
# uses dummy elements to listen for/dispatch events | |
class ControlCollectionA extends Array | |
constructor : ( arr ) -> | |
this.push( item ) for item in arr | |
this.el = document.createElement "dummy" | |
on : ( eventType, handler ) -> | |
thisEl = this.el | |
thisEl.addEventListener eventType, handler.bind( this ), false | |
for component in this | |
component.el.addEventListener eventType, ( event ) -> | |
thisEl.dispatchEvent( event ) | |
, false | |
return this | |
trigger : ( event ) -> | |
this.el.dispatchEvent event | |
return this | |
# other class methods here... | |
# Passes event listeners down the chain | |
class ControlCollectionB extends Array | |
constructor : ( arr ) -> | |
this.push( item ) for item in arr | |
on : ( eventType, handler ) -> | |
handler = handler.bind( this ) | |
for component in this | |
component.on eventType, handler | |
return this | |
trigger : ( event ) -> | |
for component in this | |
component.trigger event | |
return this | |
# other class methods here... | |
# Same ControlComponent class can be used with either collection class. | |
class ControlComponent | |
constructor : ( el ) -> | |
this.el = el | |
on : ( eventType, handler ) -> | |
this.el.addEventListener eventType, handler.bind( this ), false | |
trigger : ( event ) -> | |
this.el.dispatchEvent( event ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment