我正在创建一个 JavaScript 模块,当单击模态底部的(下一个或上一个)按钮时,当前模态(总共 4 个)将数据作为 AJAX 请求提交,然后打开下一个模态。
但是,正如您所看到的,每个子模块中的代码几乎相同(配置文件、详细信息...)。唯一的变化是“$modal”变量和两个 ajax 请求(一个用于 GET,另一个用于 POST)。
我尝试使用原型(prototype)模式(这是我第一次),但这不起作用。有解决方案的想法吗?谢谢
var application = (function() {
// cache DOM
var $modals = $('.modals');
var $buttons = $modals.find('.form_buttons');
function openModal() {
var modalId = $(this).attr('data-modal');
// Don't worry about this part, I still have to write the modal change
console.log(modalId);
}
// Profile
profile = (function() {
// cache DOM
var $modal = $modals.find('#modal_one');
// bind events
$modal.on('click', 'button.submit_button', submit);
$modal.on('click', 'button.previous_button', submit);
function submit() {
$.ajax({})
.done(function() {
openModal.call(this);
});
}
})();
// Details
details = (function() {
// cache DOM
var $modal = $modals.find('#modal_two');
// bind events
$modal.on('click', 'button.submit_button', submit);
$modal.on('click', 'button.previous_button', submit);
function submit() {
$.ajax({})
.done(function() {
openModal.call(this);
});
}
})();
// Education
education = (function() {
// cache DOM
var $modal = $modals.find('#modal_three');
// bind events
$modal.on('click', 'button.submit_button', submit);
$modal.on('click', 'button.previous_button', submit);
function submit() {
$.ajax({})
.done(function() {
openModal.call(this);
});
}
})();
// Employment
employment = (function() {
// cache DOM
var $modal = $modals.find('#modal_four');
// bind events
$modal.on('click', 'button.submit_button', submit);
$modal.on('click', 'button.previous_button', submit);
function submit() {
$.ajax({})
.done(function() {
openModal.call(this);
});
}
})();
})();
最佳答案
未经测试
var application = (function () {
// cache DOM
var $modals = $('.modals');
var $buttons = $modals.find('.form_buttons');
function fn($modal, ajaxObj) {
// bind events
$modal.on('click', 'button.submit_button', submit);
$modal.on('click', 'button.previous_button', submit);
function openModal() {
var modalId = $modal.attr('data-modal');
// Don't worry about this part, I still have to write the modal change
console.log(modalId);
}
function submit() {
$.ajax(ajaxObj)
.done(openModal);
}
}
fn($modals.find('#modal_one'), { /* obj to pass to ajax call for modal_one */ });
fn($modals.find('#modal_two'), { /* obj to pass to ajax call for modal_two */ });
//... etc...
//alternatively you could probably just loop '$modals' and call 'fn' for each of them.
//
//Also, brought 'openModal' into 'fn' which makes it a bit more maintainable imo. This is not
//required though. Instead you could just have it side outside of 'fn' and call using
//openModal.call($modal) or better: just pass $modal as a regular parameter without using 'this'.
})();
关于javascript - 如何编写一个可以适应稍微不同的用例的 JavaScript 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41225828/