genkio / blog

Stay hungry stay foolish
https://slashbit.github.io/blog/
0 stars 1 forks source link

Implement dependency injection in JavaScript with CoffeeScript #126

Open genkio opened 7 years ago

genkio commented 7 years ago
# di.coffee

# coffeescript magic: @ = this
@Hello =
  say: ->
    console.log("hello")

@Goodbye =
  say: ->
    console.log("goodbye")

Controller = (Hello, Goodbye) ->
  Hello.say()
  Goodbye.say()

# coffeescript magic: fat arrow, to ensure 'this' is pointing the correct object
injectAndExecute = (ctrl) =>
  ctrlStr = ctrl.toString()
  argumentPattern = /// # coffeescript magic: annotate regular expression
    function\s? # 0 or 1 single white space character
    \(          # (
    (.+)        # 1 or more any single character except the newline character
    \)          # )
  ///

  # coffeescript magic: use ? to check existance
  results = ctrlStr.match(argumentPattern)?[1].split(",") or []
  argumentFuncList = results.map (result) => @[result.trim()]
  ctrl.apply(this, argumentFuncList)

injectAndExecute(Controller)

# coffee di.coffee