My app has a feature that when you click the new data button, HTML is loaded to the page via ajax. Because I am using AJAX, all events I want to add has to be bound using the on()
method.
There are 4 on('click')
functions that are bound to 4 different HTML elements:
// save data
$('#container').on( {
click: function() {
// save code here
}
}, "a.save_data" );
// cancel data
$('#container').on( {
click: function() {
// cancel code here
}
}, "a.cancel_data" );
// edit data
$('#container').on( {
click: function() {
// edit code here
}
}, "a.edit_data" );
// delete data
$('#container').on( {
click: function() {
// delete code here
}
}, "a.delete_data" );
Each of these functions share multiple jQuery wrappers to select certain elements within the HTML:
$(this).closest('div.content_wrap');
$(this).closest('div.Content');
Please note: The reason I am using selectors such as $(this).closest()
is because the user has the ability to add the same HTML multiple times on to the page.
First, is there a better way to organize all of the on()
functions? Maybe combine them into one object OR create a function?
Second, because all 4 functions use the same jQuery wrappers, is there any way to declare them in a variable globally somewhere, so i don't keep retyping them. I wasn't able to figure out how declare variables with $(this)
and apply it to more than one function.
To me, how I am doing it doesn't seem very DRY and I was wondering if someone can help me better organize this.