我只是 JS 的初学者,正在从事前端工作。我编写了一些工作代码,但它让我很难维护和扩展它。我想尽可能地转向函数式编程,但我不知道如何处理我的延迟。
工作代码(创建一个模态,要求 2 个参数,然后继续使用参数,或者关闭模态而不继续):
var defer = $.Deferred();
var modal = {
class: 'modal-box',
title: 'Action required',
message: 'Please specify where to split:',
choices: [{modePK: 0, mode: 'All', checked: true},
{modePK: 1, mode: 'Right-most'},
]
};
$('body').append($('<div id="overlay_visible">'));
$('body').append($(Mustache.render($("#modal-delimiter-template").html(), modal)));
$('body').on('click', '#delimiter-submit', function () {
defer.resolve(true, $(this));
});
$('body').on('click', '#deny-forms', function () {
defer.resolve(false, $(this));
});
defer.done(function (cancelled, caller) {
if (!cancelled) { *do fancy stuff with the choice*} else { *close the modal*} });
在此示例中,延迟在两个函数中得到解决,我手动将其归因于模式中的两个按钮。现在我想转向这样的事情:
function buttonAccept() {
$('body').on('click', '#delimiter-submit', function () {
defer.resolve(true, $(this)); <- THIS ISN'T DEFINED
});
}
function buttonCancel() {
$('body').on('click', '#deny-forms', function () {
defer.resolve(false, $(this)); <- THIS ISN'T DEFINED
});
}
function showModal(modal, template, ...buttonFunctions) {
var defer = $.Deferred();
$('body').append($(Mustache.render($(template).html(), modal)));
buttonFunctions.apply(this) <--- THIS IS WHERE I AM STUCK
}
function askUserDelimiterMode () {
var modal = {
class: 'modal-box',
title: 'Action required',
message: 'Please specify where to split:',
choices: [{modePK: 0, mode: 'All', checked: true},
{modePK: 1, mode: 'Right-most'},
]
};
var template = "#modal-delimiter-template"
return showModal(modal, template, buttonAccept, buttonCancel)
};
askUserDelimiterMode().then(*do fancy stuff with the choice*);
第二个代码已经更清晰了,我可以重用东西,但不知道如何将延迟传递给buttonFunctions。 ButtonFunctions 使用 ... 运算符,因为我可能需要在前端中具有不同效果的任意数量的按钮。我绝对是这方面的初学者,如果能朝着正确的方向前进,我会很高兴。
最佳答案
当它们属于一起时,不要将它们放在不同的函数中。当然,您可以简单地将延迟对象作为参数传递给它们,但这是一种不好的做法 - 异步函数应该自己创建、解析并返回它们的 Promise。
function showModal(modal, template, ...buttons) {
const defer = $.Deferred();
$('body').append($(Mustache.render($(template).html(), modal)));
for (const [i, selector] of buttons.entries()) {
$('body').on('click', selector, function() {
defer.resolve(i, $(this));
});
}
return defer.promise();
}
function askUserDelimiterMode () {
var modal = {
class: 'modal-box',
title: 'Action required',
message: 'Please specify where to split:',
choices: [
{modePK: 0, mode: 'All', checked: true},
{modePK: 1, mode: 'Right-most'},
]
};
return showModal(modal, '#modal-delimiter-template', '#deny-forms', '#delimiter-submit');
}
askUserDelimiterMode().then(/*do fancy stuff with the choice*/);
关于javascript - 如何让另一个函数解析 jquery 延迟的函数式编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48620559/