[英]Javascript Function with Callback and Parameters
尝试添加需要使用参数运行另一个函数的回调时,我遇到了一些基本的JS函数问题。
这是我的电子邮件功能:
function sendEmail(template, to, cc, bcc, callback, optional=null){
// Define vars needed
var body = '',
subject = '';
// Based on the template..
switch(template){
case 'privateNote':
// Define the subject
subject = 'Tool Request - Private Note Added';
// Define our body
body += 'Hello, <br /><br />';
body += 'A new private note has been added to Request #' + requestID + '.<br/><br/>';
body += 'To visit the request, click the following link: <a href="' + window.location.protocol + "//" + window.location.host + "/tool/Request2.php?id=" + requestID + '">' + window.location.protocol + "//" + window.location.host + "/tool/Request2.php?id=" + requestID + '</a>.';
body += '<br /><br />';
body += '<em>Message created by ' + userFirst + ' ' + userLast + '</em>';
}
// Send our email
$.ajax({
url: "../resources/Classes/class.email.php",
type: "POST",
cache: false,
data: {
from: "noreply@domain.com",
to: to,
cc: cc,
bcc: bcc,
subject: subject,
body: body
},
error: function(err) {
alert(err.statusText);
},
success: function(data) {
// Handle Callback
callFunction(callback);
}
});
}
// Callbacks
function callFunction(func) {
func();
}
// Reload the page
function refresh(){
location.reload('true');
}
这就是我使用函数的方式:
sendEmail('privateNote', toArray, '', '', refresh, obj);
一切都按预期工作,但是我面临一个问题。
在一个部分中,我需要同时发送两封电子邮件,一封给添加到请求中的人,一封给从请求中删除的人。
我试图做的是:
var remove = sendEmail('privateNote', toArray, '', '', refresh, obj);
// Trigger Email to those who are added to the request
// However, I was trying to send a the other email with params as a callback instead of refreshing the page.
sendEmail('privateNote', toArray, '', '', remove, obj);
执行此操作时出现的问题是,似乎同时触发了两个事件,而没有等待一个事件完成,从而导致一些异步问题。
有没有办法正确地做到这一点? 我知道这可能不是处理电子邮件的最漂亮方法,但是到目前为止,当一次只需要处理一封电子邮件时,一切都可以正常工作。
这将立即调用sendEmail()
函数:
var remove = sendEmail('privateNote', toArray, '', '', refresh, obj);
由于sendEmail()
不返回任何内容,因此remove
是undefined
。
要使其成为适当的回调,请将其包装在function()
:
var remove = function() {
sendEmail('privateNote', toArray, '', '', refresh, obj);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.