Skip to content

Instantly share code, notes, and snippets.

@stevekane
Created August 27, 2013 16:44
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save stevekane/6356006 to your computer and use it in GitHub Desktop.
Save stevekane/6356006 to your computer and use it in GitHub Desktop.
ClickElsewhereMixin (an Ember mixin used to detect clicks outside a view) Original Attribution: Alex Speller's gist at https://gist.github.com/alexspeller/6251054
#original attribution https://gist.github.com/alexspeller/6251054
bound = (fnName) -> Ember.computed fnName -> @get(fnName).bind(@)
App.ClickElsewhereMixin = Ember.Mixin.create
#use this method hook to define your desired behavior
onClickElsewhere: Ember.K
#bound version of our instance method
clickHandler: bound "elsewhereHandler"
#logic for determining of a click has landed anywhere but our view
elsewhereHandler: (e) ->
element = @get "element"
$target = $ e.target
thisIsElement = $target.closest(element).length is 1
unless thisIsElement then @onClickElsewhere event
#attach event listener to window when view in DOM
didInsertElement: ->
@_super.apply(@, arguments)
$(window).on "click", @get "clickHandler"
#remove window event listener when view removed from DOM
willDestroyElement: ->
$(window).off "click", @get "clickHandler"
@_super.apply(@, arguments)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment