I needed to perform a differnt action when an ajax call was completed depending on which event handeler was fired.
Here is what I have come up with:
// create object to manipulate later
save = {
save_to_db: function () {
$.ajax({
...snip...
success: function (result) {
save.callback();
}
})
},
callback: function () {
console.log('default callback');
}
};
// normal useage
$('#b_save').click(function (e) {
save.save_to_db()
});
// one off special useage
$('#b_add_to_basket').click(function (e) {
e.preventDefault();
save.old_callback = save.callback();
save.callback = function () {
console.log('overridden call back baby!!')
}
save.save_to_db();
save.callback = save.old_callback();
});
This question: Javascript callback functions with ajax passes in the callback function, maybe I am missing how to have a default callback that can be overwritten.
My question is, is there a better way to acomplish this, and can it be optimised at all?