aurelia-bs-modal
aurelia-bs-modal copied to clipboard
handle escape function (working TypeScript code included)
i'd like to get a callback when escape function is called. I'll provide my implementation bellow:
-
I'm using it as fowollows
<modal showing.bind="showing" escape-callback.call="escapeCallback()">
-
i changed modal.js so that it
- accepts bindable escapeCallback
- registers a keyboard handler when modal is shown (
(attached and showing) or state changes to showing = true
): - unregisters keyboard handler when modal is hidden or detached
My implementation is following (My source is in TypeScript instead of ES6 that is used in this project - but it is quite strait-forward to port it back to ES6):
import {inject, customElement, bindable} from 'aurelia-framework';
import * as $ from 'jquery';
@customElement('modal')
@inject(Element)
export class Modal {
@bindable showing = false;
@bindable escapeCallback: () => void;
private keydownHandler;
private modal: Element;
constructor(private element: Element) {
}
attached(){
$(this.modal).modal({show: false});
if(this.showing) {
this.addEscHandler();
}
}
detached() {
this.removeEscHandler();
}
showingChanged(newValue){
if (newValue) {
this.addEscHandler();
$(this.modal).modal('show')
} else {
$(this.modal).modal('hide')
this.removeEscHandler();
}
}
addEscHandler() {
if(this.escapeCallback && !this.keydownHandler) {
this.keydownHandler = (e: JQueryEventObject) => {
if(e.which == 27) { // escape was pressed
this.escapeCallback();
}
};
$(this.modal).on("keydown.dismiss.bs.modal", this.keydownHandler);
}
}
removeEscHandler() {
if(this.keydownHandler) {
$(this.modal).off("keydown.dismiss.bs.modal", this.escapeCallback);
this.keydownHandler = null;
}
}
}