Let's say we've got a javascript function that is set to run whenever a delete button on the screen is clicked...
function deleteThis(obj) {
/*work to delete object*/
window.location="newurl.php";
}
$('.delete').click(function(){
deleteThis($(this));
});
<div class='delete'>Delete</div>
Now let's say you want different types of delete buttons. They all do the first few things the same, but the last step is different. What I've been doing is this...
function deleteThis(obj) {
/*standard work to delete object*/
if (obj.attr('type')=='a') {
//extra work for type a
} else if (obj.attr('type')=='b') {
//extra work for type b
}
window.location="newurl.php";
}
$('.delete').click(function(){
deleteThis($(this));
});
<div class='delete' type='a'>Delete</div>
Which works fine with just a few different types. But it's starting to get a little out of control. What I'd like is to be able to do this...
In my main javascript.js file:
function deleteThis(obj) {
/*standard work to delete object*/
/*do any extra functions that have been designated for this type*/
window.location="newurl.php";
}
$('.delete').click(function(){
deleteThis($(this));
});
Code included only on the pages where there's a "type a" button
$(document).ready(function(){
/*something that tells the deleteThis() function that it should do something extra when running*/
});
That way I wouldn't have to pass any extra variables to deleteThis(), I wouldn't have to make different onclick events for the different types of delete buttons. I could just have one type of delete button. Then on the pages where I want the delete button to behave different, all I have to do is put an extra bit of javascript code once.
Is something like this possible?
UPDATE
Note that at the end of deleteThis() is a window redirect. That makes it so any extra click handlers won't get fired because we'll have already gone away from the page.