yaodong
7/18/2016 - 4:34 AM

jquery-ajax-modal.js

const $ = require('jquery');

class Modal {

    constructor($trigger) {
        this.trigger = $trigger;
        this.target = $trigger.data('target');
        this.id = this.target.slice(1);

        if (!$(this.target).length) {
            this.createBlank();
        }

        this.modal = $(this.target);

        this.modal.on('show.bs.modal', ()=> {
            this.updateModalContent();
            this.modal.focus();
        });

        this.modal.on('hidden.bs.modal', ()=> {
            this.modal.find('.modal-content').html(this.blankContentTemplate());
        })
    }

    updateModalContent() {
        const url = this.trigger.data('url');
        if (!url) {
            return false;
        }

        $.get({
            url: url
        }).done((response) => {
            this.modal.find('.modal-content').html(response);
            this.bindForm();
        }).fail(() => {
            console.log('err');
        });
    }

    bindForm() {
        const $form = this.modal.find('form');
        const $model = this.modal;
        $form.submit((event)=> {
            event.preventDefault();
            $.ajax({
                type: "POST",
                url: $form.attr('action'),
                data: $form.serialize(),
                success: (response)=> {
                    $model.modal('hide');
                    if (response['link']) {
                        window.location.replace(response['link']);
                    }
                },
                error: (response)=> {
                    $model.find('.modal-content').html(response.responseText)
                }
            });
            return false;
        });
    }

    createBlank() {
        $('body').append(this.blankTemplate());
    }

    blankTemplate() {
        return `
<div class="modal fade" id="${this.id}" tabindex="-1" role="dialog" aria-labelledby="${this.id}Label">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      ${this.blankContentTemplate()}
    </div>
  </div>
</div>`
    }

    blankContentTemplate() {
        return `<div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
            aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="${this.id}Label">Loading</h4>
      </div>
      <div class="modal-body">
        <p>{ loading animation here }</p>
      </div>
      <div class="modal-footer">
      </div>`
    }
}

module.exports = Modal;