Skip to content

Instantly share code, notes, and snippets.

@monokrome
Last active January 9, 2018 15:00
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save monokrome/7607841 to your computer and use it in GitHub Desktop.
Save monokrome/7607841 to your computer and use it in GitHub Desktop.
Interfaces in CoffeeScript
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