Created
July 18, 2016 04:34
-
-
Save yaodong/a8be1c14617fb4a3567139e5cf1e8fc5 to your computer and use it in GitHub Desktop.
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
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">×</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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment