我想弄清楚如何創建一個具有多個回調函數的最佳方式。JS函數與回調數組
總之,我始終能夠發送電子郵件時所採取的關鍵行動應用不同的觸發(當單被關閉或成員已被分配給它,如)。棘手的部分是有時需要同時發送多個不同的電子郵件。
這裏是我的電子郵件功能:
function sendEmail(template, to, cc, bcc, callback, optional=null){
// Define vars needed
var body = '',
subject = '';
// Based on the template..
switch(template){
case 'updatedTask':
// Define the subject
subject = 'Tool Request - Updated Task';
// Define our body
body += 'Hello, <br /><br />';
body += 'Blah Blah';
body += 'Footer';
break;
case 'removedTaskOwner':
// Define the subject
subject = 'Tool Request - Removed Task Owner';
// Define our body
body += 'Hello, <br /><br />';
body += 'Blah Blah';
body += 'Footer';
break;
case 'completedTask':
// Define the subject
subject = 'Tool Request - Completed Task';
// Define our body
body += 'Hello, <br /><br />';
body += 'Blah Blah';
body += 'Footer';
break;
}
// 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');
}
這是我目前使用的功能:
// Once the email is sent, it triggers a function called refresh
sendEmail('taskUpdated', toArray, '', '', refresh, '');
這就是我要做的:
// Define our remove function as a callback
var remove = function() {
sendEmail('removeTaskOwner', toArray, '', '', refresh, '');
}
// Define our completed function as a callback
var completed = function() {
sendEmail('completedTask', toArray, '', '', refresh, '');
}
// If there is a completed date, we need to send out two separate emails
var callbacks = Array();
if(completionDate){
callbacks.push('completed', 'remove');
}else{
callbacks.push('remove');
}
sendEmail('taskUpdated', toArray, '', '', callbacks, '');
的我遇到的問題是,它不會出現callbacks
可以是一個回調函數的數組。
的什麼,我試圖做的總體需要的功能是通過多個templates
& recipients
,有一個最終的功能在郵件的末尾被觸發發送出去,比如頁面清爽的能力。
'callback'可以是一個數組,但你必須把它當作這樣的。你正試圖調用這個數組作爲一個函數。 – Kenney