2015-11-11 128 views
1

当我试图添加一个需要用params运行另一个函数的回调函数时,我遇到了一些基本JS函数的问题。带回调和参数的Javascript函数

这里是我的电子邮件功能:

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: "[email protected]", 
     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); 

问题这样做是,它似乎没有等待一个完成造成一些异步问题有待发射都在同一时间。

有没有办法正确地做到这一点?我知道这可能不是处理电子邮件最好的方式,但是一次只能处理一封电子邮件时,一切运行良好。

回答

4

这立即调用sendEmail()功能:

var remove = sendEmail('privateNote', toArray, '', '', refresh, obj); 

由于sendEmail()不返回任何东西,removeundefined

要使它成为一个适当的回调,在function()包装它:

var remove = function() { 
    sendEmail('privateNote', toArray, '', '', refresh, obj); 
} 
+2

这工作完美,很好地完成。 – SBB