consul/ui-v2/app/mixins/click-outside.js
John Cowen 2920f73ddd ui: Adds document and viewport methods to the dom service (#5052)
`window` and `document` are easily injected anyhow, but this
primarily this keeps everything dom related in the same place.

Included here are changes to make all ember related objects use the dom
service `document` and `viewport` instead of just `document` and
`window`.

Quote from a previous PR (#4924) which explains the thinking around this:

> Now I have all these things in the dom service, it would make sense
to get window from there also. I was thinking of making a viewport
method, which would be a nice word whether window was a browser window,
an iframe (not really a window) like when ember testing, or anything
else. To me the viewport is what we are actually talking about here.
2019-05-01 18:21:57 +00:00

44 lines
1.2 KiB
JavaScript

import Mixin from '@ember/object/mixin';
import { inject as service } from '@ember/service';
import { next } from '@ember/runloop';
import { get } from '@ember/object';
// TODO: Potentially move this to dom service
const isOutside = function(element, e, doc = document) {
if (element) {
const isRemoved = !e.target || !doc.contains(e.target);
const isInside = element === e.target || element.contains(e.target);
return !isRemoved && !isInside;
} else {
return false;
}
};
const handler = function(e) {
const el = get(this, 'element');
if (isOutside(el, e)) {
this.onblur(e);
}
};
export default Mixin.create({
dom: service('dom'),
init: function() {
this._super(...arguments);
this.handler = handler.bind(this);
},
onchange: function() {},
onblur: function() {},
didInsertElement: function() {
this._super(...arguments);
const doc = get(this, 'dom').document();
next(this, () => {
doc.addEventListener('click', this.handler);
});
},
willDestroyElement: function() {
this._super(...arguments);
const doc = get(this, 'dom').document();
doc.removeEventListener('click', this.handler);
},
});