Skip to content

Commit

Permalink
fix: click outside dropdown (#1013)
Browse files Browse the repository at this point in the history
Co-authored-by: Lee Chase <[email protected]>
  • Loading branch information
lee-chase and lee-chase authored Sep 9, 2020
1 parent af1e300 commit 9a1ff2c
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 8 deletions.
13 changes: 5 additions & 8 deletions packages/core/src/components/cv-dropdown/cv-dropdown.vue
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
@keydown.esc.prevent="onEsc"
@keydown.tab="onTab"
@click="onClick"
v-clickout="onClickout"
ref="listbox"
>
<button
Expand Down Expand Up @@ -120,10 +121,12 @@ import CvDropdownItem from './cv-dropdown-item';
import WarningFilled16 from '@carbon/icons-vue/es/warning--filled/16';
import ChevronDown16 from '@carbon/icons-vue/es/chevron--down/16';
import carbonPrefixMixin from '../../mixins/carbon-prefix-mixin';
import clickout from '../../directives/clickout';

export default {
name: 'CvDropdown',
inheritAttrs: false,
directives: { clickout },
mixins: [themeMixin, uidMixin, carbonPrefixMixin, methodsMixin({ button: ['blur', 'focus'] })],
components: { WarningFilled16, ChevronDown16, CvDropdownItem },
props: {
Expand Down Expand Up @@ -165,17 +168,13 @@ export default {
this.$on('cv:beforeDestroy', srcComponent => this.onCvBeforeDestroy(srcComponent));
},
mounted() {
document.body.addEventListener('click', this.checkClickOut);
this.updateChildren(this.internalValue);
this.checkSlots();
},
beforeUpdate() {
document.body.removeEventListener('click', this.checkSlots);
this.checkSlots();
},
beforeDestroy() {
document.body.removeEventListener('click', this.checkSlots);
},
model: {
prop: 'value',
event: 'change',
Expand Down Expand Up @@ -230,10 +229,8 @@ export default {
},
},
methods: {
checkClickOut(ev) {
if (ev.target === null || !this.$refs.listbox.contains(ev.target)) {
this.open = false;
}
onClickout(ev) {
this.open = false;
},
updateChildren(val) {
const childItems = this.dropdownItems();
Expand Down
17 changes: 17 additions & 0 deletions packages/core/src/directives/clickout.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// This directive determines calls the associated method if a click happens outside of el

export default {
bind(el, binding, vnode) {
el.clickOutHandler = function(event) {
// neither element or child of
if (!(el == event.target || el.contains(event.target))) {
// call method
vnode.context[binding.expression](event);
}
};
document.body.addEventListener('click', el.clickOutHandler);
},
unbind(el) {
document.body.removeEventListener('click', el.clickOutHandler);
},
};

0 comments on commit 9a1ff2c

Please sign in to comment.