I am trying to figure out how the best way to go about creating a function with multiple callbacks.
In short, I have different triggers throughout an application that can send out emails when key actions are taken (such as when a ticket is closed or a member has been assigned to it). The tricky part is that multiple different, emails needs to go out at the same time on occasion.
Here is my email function:
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');
}
This is how I use the function currently:
// Once the email is sent, it triggers a function called refresh
sendEmail('taskUpdated', toArray, '', '', refresh, '');
This is what I am trying to do:
// 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, '');
The issue I am running into is that it doesn't appear callbacks can be an array of callback functions.
The overall needed feature of what I am trying to do is the ability to pass multiple templates & recipients and have a final function be triggered at the end of the emails being sent out, such as the page refreshing.
callbackcan be an array, but you must treat it as such. You're attempting to invoke the array as a function.