plwalters / aurelia-bs-modal

DEPRECATED - Aurelia plugin for bootstrap modal
MIT License
17 stars 16 forks source link

handle escape function (working TypeScript code included) #16

Open atsu85 opened 9 years ago

atsu85 commented 9 years ago

i'd like to get a callback when escape function is called. I'll provide my implementation bellow:

1) I'm using it as fowollows <modal showing.bind="showing" escape-callback.call="escapeCallback()">

2) i changed modal.js so that it

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;
    }
  }
}
atsu85 commented 8 years ago

to resolve this issue, please merge my pull request https://github.com/PWKad/aurelia-bs-modal/pull/34 and run gulp build to update dist folder