-define 'elyssa/events', ->
+define 'elyssa/events', ['root'], ->
   'use strict'
   
   class EventMap
-    eventMap = {}
-    eventFunctions = {}
    
     constructor: (@sender) ->
-      eventMap = {}
-      eventFunctions = {}
-    
-    validEvents: []
+      @events = {}
+      @validEvents = []    
 
     on: (eventName, eventFunction) ->
       return unless eventFunction
 
       if @validEvents.length > 0
-        return if validEvents.indexOf(eventName) is -1
+        return if @validEvents.indexOf(eventName) is -1
       
       eventDesc = 
         event: eventFunction


      # Differentiate between eventName being an object or a string
      if typeof eventName is 'object'
        {name, interval, repeat, context} = eventName
      else
        name = eventName

      # Break if event doesn't exist
      return unless eventMap[name]

      # Set default values
      interval = 0 unless interval?
      repeat = false unless repeat?
      context = @ unless context?
      
      # Walk through all events and call them
      for i in eventMap[name]
        triggerFunction = (evObject) -> 
          i.event.apply context, [[i.sender], args].reduce((a, b) -> a.concat(b))
        
        if interval      
          if repeat
            i.type = 'repeat'
            i.id = window.setInterval triggerFunction, interval
          else
            i.type = 'once'
            i.id = window.setTimeout triggerFunction, interval
        else
          i.type = 'direct'
          triggerFunction.call @

      @
    

        type: ''
        sender: @sender
      
      unless @events[eventName]
        @events[eventName] = [eventDesc]
      else
        @events[eventName].push eventDesc
      
      @
      
    off: (eventName) -> 
      return unless eventName    

      if @events[eventName].type is 'once' or @events[eventName].type is 'repeat'
        root.clearInterval @events[eventName].id if @events[eventName].type is 'repeat'
        root.clearTimeout @events[eventName].id if @events[eventName].type is 'once'

      delete @events[eventName] if @events[eventName]

      @
    
