Skip to content

Instantly share code, notes, and snippets.

@AlexandreBonneau
Created October 18, 2016 08:50
Show Gist options
  • Save AlexandreBonneau/af8321c8dcc21c646eea74ee8d672f23 to your computer and use it in GitHub Desktop.
Save AlexandreBonneau/af8321c8dcc21c646eea74ee8d672f23 to your computer and use it in GitHub Desktop.
Vue 2 directive that allows the user to cancel a text input change with 'Escape' - Work in progress
directives: {
cdzCancellable: { //FIXME finish this
bind(el, bindings, vnode, oldVnode) {
console.log(`cdzCancellable attached!`, el, el.type, bindings, vnode, oldVnode); //DEBUG
if (el.type === 'radio' || el.type === 'checkbox') {
return;
}
let oldValue;
let isAutoNumericInput = false;
function _saveCurrentElementValue(elm) {
if (_isCdzNumericNode(elm)) {
oldValue = elm.autoNumeric('get');
}
else {
oldValue = elm.value;
}
}
function _isCdzNumericNode(elm) { //FIXME finish this stub
isAutoNumericInput = false;
return false;
}
function _selectInputText(e) {
e.target.select();
}
el.addEventListener("keyup", function(e) {
let elm = e.target;
oldValue = null;
if (e.keyCode === keyCode.Esc) {
e.preventDefault();
if (isAutoNumericInput && ("" === oldValue)) {
oldValue = 0;
}
let currentValue = elm.value;
if (currentValue === oldValue) {
console.log(`The value has not changed`, currentValue, oldValue); //DEBUG
}
else {
console.log(`The value has changed from ${oldValue} to ${currentValue}`); //DEBUG
elm.value = oldValue;
}
_selectInputText(e);
this.$emit('escapePressed'); //FIXME this does not work since 'this' is undefined
}
if (e.keyCode === keyCode.Enter) {
_saveCurrentElementValue(e.target);
}
});
el.addEventListener("focus", function(e) {
_saveCurrentElementValue(e.target);
});
//FIXME Remove the listeners on destroy
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment