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. and they look like this:
// 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. Like this:
$(this).closest('div.content_wrap');
$(this).closest('div.Content');
(please note, that 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.
Thanks a lot
EDIT
This is what I came up with
var elements = ["a.save_data", "a.cancel_data", "a.delete_data", "a.edit_data"];
$.each(elements, function(i, el)
{
$('#container').on('click', el, function()
{
// Variables to be used in all if statements below
var var1 = value
var2 = value
// Save Data
if (el == "a.save_data") {
// save code
}
// Cancel Data
else if (el == "a.cancel_data") {
// cancel code
}
// Edit Data
else if (el == "a.qEdit") {
// edit code
}
// Delete Data
else if (el == "a.qDelete") {
// delete code
}
return false;
});
});
EDIT
var handlers = {
test: function(f, n, t) {
f.hide();
n.hide();
t.text("hidden");
}
}
$('button').on('click', function() {
var selector = $(this).prop('id'),
first = $(this).prev(),
next = $(this).next(),
top = $(this).closest('div.top');
handlers[selector](first, next, top);
});
This code executed exactly the same as:
var handlers = {
test: function(e, f, n, t) {
f.hide();
n.hide();
t.text("hidden");
}
}
$('button').on('click', function(event) {
var selector = $(this).prop('id'),
first = $(this).prev(),
next = $(this).next(),
top = $(this).closest('div.top');
handlers[selector].call(this, event, first, next, top);
});