-
-
Save waghcwb/177f7f4b614b8937117f48b862cacc0a to your computer and use it in GitHub Desktop.
Interfaces in CoffeeScript
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
class Host | |
constructor: -> | |
interfaces = @constructor.interfaces | |
if interfaces? | |
for interface in interfaces | |
_.extend @, interfaces | |
@implements: (host, interface) -> | |
# This effectively makes host optional | |
unless interface? | |
interface = host | |
host = @ | |
host.interfaces ?= [] | |
for name, property of interface | |
if _.isFunction property | |
requisite = property() | |
else | |
requisite = property | |
unless name of host | |
throw new Error """ | |
The #{ name } interface requires an implementation | |
of #{ name }, but one was not provided for | |
#{ host.name }. | |
""" | |
implementation = host[name] | |
# TODO: Validate requisite. | |
host.interfaces.push interface | |
Events = | |
on: | |
arguments: ['string', 'function'] | |
# Example leveraging a Base class | |
class Fruit extends InterfaceHost | |
@implements Events | |
# Example without a Base class | |
class Vehicle | |
constructor: -> Host.apply @ | |
# Using arguments: | |
Host.implements Vehicle, Events | |
# or by applying context: | |
Host.implements.apply Vehicle, Events |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment