class NewDocumentModal { constructor() { this.$modal = $("#new-document-modal"); this.modal = bootstrap.Modal.getInstance(this.$modal.get(0)); this.$modal.on("show.bs.modal", event => this.onShow(event)); this.$modal.on("shown.bs.modal", () => this.onShown()); this.$modal.on("hidden.bs.modal", () => this.onHidden()); this.$title = this.$modal.find(".modal-title"); this.$form = this.$modal.find("form"); this.$form.on("submit", event => this.onSubmit(event)); this.$typeField = this.$form.find("[name=type]"); this.$locationDropdown = this.$form.find("[name=location_id]"); this.$supplierDropdown = this.$form.find("[name=supplier_id]"); } // Modal lifecycle onShow(event) { const $element = $(event.relatedTarget); const data = $element.data(); const { type } = data; switch(type) { case 2: // Goods-In this.$title.text("New Goods-In"); this.baseUrl = "/goods-in"; break; case 3: // ARU this.$title.text("New ARU"); this.baseUrl = "/arus"; break; } } onShown() { this.$supplierDropdown.trigger("focus"); } onHidden() { this.$form.get(0).reset(); this.$typeField.val(null); } onSubmit(event) { event.preventDefault(); const data = this.$form.serialize(); $.post(`${this.baseUrl}/create`, data).then(response => { this.$modal.modal("hide"); window.location = response.url; }).catch(error => { console.log(error); }); } } $(() => new NewDocumentModal());