Menu.coffee 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. class Menu
  2. constructor: (@button) ->
  3. @elem = $(".menu.template").clone().removeClass("template")
  4. @elem.appendTo("body")
  5. @items = []
  6. show: ->
  7. if window.visible_menu and window.visible_menu.button[0] == @button[0] # Same menu visible then hide it
  8. window.visible_menu.hide()
  9. @hide()
  10. else
  11. button_pos = @button.offset()
  12. left = button_pos.left
  13. @elem.css({"top": button_pos.top+@button.outerHeight(), "left": left})
  14. @button.addClass("menu-active")
  15. @elem.addClass("visible")
  16. if @elem.position().left + @elem.width() + 20 > window.innerWidth
  17. @elem.css("left", window.innerWidth - @elem.width() - 20)
  18. if window.visible_menu then window.visible_menu.hide()
  19. window.visible_menu = @
  20. hide: ->
  21. @elem.removeClass("visible")
  22. @button.removeClass("menu-active")
  23. window.visible_menu = null
  24. addItem: (title, cb) ->
  25. item = $(".menu-item.template", @elem).clone().removeClass("template")
  26. item.html(title)
  27. item.on "click", =>
  28. if not cb(item)
  29. @hide()
  30. return false
  31. item.appendTo(@elem)
  32. @items.push item
  33. return item
  34. log: (args...) ->
  35. console.log "[Menu]", args...
  36. window.Menu = Menu
  37. # Hide menu on outside click
  38. $("body").on "click", (e) ->
  39. if window.visible_menu and e.target != window.visible_menu.button[0] and $(e.target).parent()[0] != window.visible_menu.elem[0]
  40. window.visible_menu.hide()