Tuesday, 28 May 2013

Simple Event Manager In CoffeeScript

Over the past few days I have been messing with CoffeeScript and web stuff. It is really just for fun to get myself back into programming at home after nearly a month off. Bashing together some parts of  a simple 2D game platform in CoffeeScript sure is fun.

Today I wrote a simple EventSystem where you can add/remove listeners and fire/dispatch events. It is not complicated. The contrast between the code here and what you would have to do in say Java is pretty striking. Each language has it's own trade offs and CoffeeScript (read as dynamic languages) shines quite well here.

class EventManager
  constructor:() ->
    @listeners = {}

  fire:(name, data)->
    console.log 'firing'
    for lis in @listeners[name]

  dispatch:(name, data) -> fire(name, data)

  add:(name, listener) ->
    if name of @listeners
      @listeners[name] = [listener]

    for name,lis of @listeners
      idx = lis.indexOf(listener)
      if idx != -1
        lis.splice(idx, 1)

  removeAll:() ->
    @listeners = {}

This use case is pretty much this

$ ->
  em = new EventManager()

  listener = (d)->
    console.log "event lis", d

  em.add "test", listener
  em.fire('test', 100)
  em.remove listener
  em.fire('test', 'this should not be printed')

I appreciate I could remove a lot more brackets in my code shown. I am still dabbling with how many brackets I like to see in my code. Sometimes having them there makes it feel more readable to my tried brain. Years of coding C/C++/Java take their toll.

No comments:

Post a Comment