ContextMenu.coffee 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. define [
  2. "libs/backbone"
  3. "libs/mustache"
  4. ], () ->
  5. ContextMenuEntry = Backbone.View.extend
  6. template: $("#contextMenuEntryTemplate").html()
  7. events:
  8. "click a" : "onClick"
  9. render: () ->
  10. @setElement($(Mustache.to_html(@template, @options)))
  11. return @
  12. onClick: (e) ->
  13. e.preventDefault()
  14. if @options.onClick
  15. @options.onClick()
  16. ContextMenu = Backbone.View.extend
  17. templates:
  18. menu: $("#contextMenuTemplate").html()
  19. divider: $("#contextMenuDividerTemplate").html()
  20. initialize: (position, entries) ->
  21. if ContextMenu.currentMenu?
  22. ContextMenu.currentMenu.destroy()
  23. ContextMenu.currentMenu = @
  24. @render()
  25. for entry in entries
  26. @addEntry(entry)
  27. @show(position)
  28. render: () ->
  29. @setElement($(@templates.menu))
  30. $(document.body).append(@$el)
  31. return @
  32. destroy: () ->
  33. @$el.remove()
  34. @trigger "destroy"
  35. show: (position) ->
  36. page = $(document.body)
  37. page.on "click.hideContextMenu", (e) =>
  38. page.off "click.hideContextMenu"
  39. @destroy()
  40. @$el.css
  41. position: "absolute"
  42. "z-index": 10000
  43. @$el.css position
  44. addEntry: (options) ->
  45. if options.divider
  46. @$el.append $(@templates.divider)
  47. else
  48. entry = new ContextMenuEntry(options)
  49. @$el.append entry.render().el