Created
December 14, 2016 02:25
-
-
Save jbruni/6a879ae2313c2713c71881617089ff23 to your computer and use it in GitHub Desktop.
v-click-outside directive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* v-click-outside directive | |
*/ | |
import Vue from 'vue' | |
import $ from 'jquery' | |
let elements = [] | |
Vue.directive('click-outside', { | |
bind: (el, binding) => { | |
bindClickOutside(el, binding.value) | |
}, | |
unbind: (el, binding) => { | |
unbindClickOutside(el) | |
} | |
}) | |
function bindClickOutside(el, handler) { | |
elements.push({ el, handler }) | |
} | |
function unbindClickOutside(el) { | |
$.each(elements, (index, item) => { | |
if (item.el === el) { | |
elements.splice(index, 1) | |
return false | |
} | |
}) | |
} | |
$(document).on('click', (e) => { | |
elements.forEach(item => { | |
let $el = $(item.el) | |
if (!$el.is(':animated') | |
&& $el.is(':visible') | |
&& $(e.target).closest(item.el).length === 0 | |
) { | |
item.handler(e) | |
} | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment