Created
November 15, 2018 13:34
-
-
Save DV8FromTheWorld/f6e8524b5ee7c3db3e8c7a7dc2c43419 to your computer and use it in GitHub Desktop.
Enhanced Selects
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
// selects do not fire change events if their value or selectedIndex is updated directly (only if their _options_ change), | |
// unfortunately, js frameworks typically update selects via direct calls to the value or selectdIndex. We need to be able to fire an event | |
// for either of these when they are set so we can communicate the changes to the choices.js library. | |
function enhanceSelectPrototype() { | |
if (HTMLSelectElement.prototype.__inmHasBeenEnhanced) { | |
return | |
} | |
const valueDescriptor = Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'value') | |
const selectedIndexDescriptor = Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'selectedIndex') | |
Object.defineProperty(HTMLSelectElement.prototype, 'value', { | |
get() { | |
return valueDescriptor.get.call(this) | |
}, | |
set(newValue) { | |
var event = new CustomEvent("inm-select-changed", { | |
detail: { | |
value: newValue | |
} | |
}) | |
this.dispatchEvent(event) | |
valueDescriptor.set.call(this, newValue) | |
}, | |
enumerable: true, | |
configurable: true | |
}) | |
Object.defineProperty(HTMLSelectElement.prototype, 'selectedIndex', { | |
get() { | |
return selectedIndexDescriptor.get.call(this) | |
}, | |
set(newValue) { | |
// give "this" enough time to actually set it's value | |
setTimeout(function(){ | |
var event = new CustomEvent("inm-select-changed", {}) | |
this.dispatchEvent(event) | |
}.bind(this), 2) | |
selectedIndexDescriptor.set.call(this, newValue) | |
}, | |
enumerable: true, | |
configurable: true | |
}) | |
HTMLSelectElement.prototype.__inmHasBeenEnhanced = true | |
} | |
enhanceSelectPrototype() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment