Created
May 30, 2011 13:47
-
-
Save bremac/998920 to your computer and use it in GitHub Desktop.
Hal-baked ideas on Injectors. All legal but unusual coffee-script
This file contains 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
inspect = (o) -> | |
alert(JSON.stringify(o)) | |
# GWT-style module injection | |
class Module | |
constructor: (m) -> | |
@extend(m) | |
extend: (m) -> | |
for k, v of m | |
@[k] = v | |
@ | |
create: (type) -> | |
@inject(new type(), type.INJECTED) | |
inject: (obj, dict) -> | |
if dict? | |
for name, factory of dict | |
obj[name] = @[factory](@) | |
obj | |
main = new Module | |
Foo: -> 'FOO FACTORY RESULT' | |
Bar: -> 'BAR FACTORY RESULT' | |
class Baz | |
@INJECTED = | |
foo: 'Foo' | |
bar: 'Bar' | |
myBaz = main.create(Baz) | |
# Monkey-patching interface | |
class Interface | |
NOT_IMPLEMENTED = -> throw 'not implemented' | |
__impl__: NOT_IMPLEMENTED | |
constructor: -> | |
@__impl__() | |
@use: (type) -> | |
unless @::__impl__ is NOT_IMPLEMENTED | |
throw 'Rebinding of bound interface attempted' | |
@::__impl__ = type | |
for k, v of type | |
@[k] = v | |
for k, v of type:: | |
@::[k] = v | |
@ | |
class Foo extends Interface | |
usesFoo = -> | |
f = new Foo() | |
f.hi() | |
class Bar | |
constructor: -> | |
@greeting = 'Hello' | |
hi: -> alert('hi') | |
Foo.use(Bar) | |
f = new Foo() | |
f.hi() | |
alert(f.greeting) | |
# Of course, usesFoo works too: | |
usesFoo() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment