Background: I'm loading some resources via ajax
, using promisses with $.when.apply
, doing other requisitions when the previous are done. I'm dynamically loading some jQuery Mobile Collapsibles
and some content inside them.
When I click in a specific content with a link, he have to open his destination and save an value of a custom atribute that I created to store data(data-id
).
Problem: Each time that I open another collapsible, then click in this link inside, the click is called 1 time PLUS the number of diferents collapsibles that I opened previously, and consequently leading to error, that is calling the requisitions multiple times.
Here's an image to make more clear:
CODE:
$.when.apply(null, [buildTasks(curr_user)]).done(function () {
//make the requisition. If it's not empty, then...
if( !isEmpty( $('#posts_dates') ) ){
$('#pg_tasks').on("collapsibleexpand", "[data-role=collapsible]", function (e) {
/*Checks if the collapsible have data inside
a custom created attribute, data-date
If yes, saves this data in a variable(temp_data),
do the ajax requisition , empty temp_data and empty
data-date, so the requisition won't be called again for this collapsible .*/
if ( $(this).attr('data-date') !== '' ){
var temp_data = $(this).attr('data-date');
var temp_id = $(this).attr('id');
buildTasksPosts(curr_user,temp_data,temp_id);
//loads the content via ajax when a collapsible is expanded
temp_data = '';
temp_id = '';
$(this).attr('data-date','');
$.when.apply(null, [buildTasksPosts() ]).done(function () {
/*after the requisition is done, enable a handler
on the current page for the links with a custom attribute data-id*/
$( "#pg_tasks" ).on( "click","a[data-id]", function() {
var p_id = '';
//THE ERROR can be seen here when I use the console
console.log('DATA-ID: '+ $( this ).attr('data-id') );
p_id = $( this ).attr('data-id');
buildTasksDetail(p_id);
});
});
}else{
console.log('AVISO:não fiz nada!!');
}
});
}//end if
});
Any ideas? I really don't know what is causing this.
The problem is that you are adding a click handler to all "a[data-id]"
children of $("#pg_tasks")
every time a collapsible is expanded. That is why your click events keep firing plus one times.
Instead of adding the click handler within the collapsibleexpand
of each collapsible, you can add it just once and let event delegation work. So as soon as #pg_tasks exists in the DOM, you can attach the handler:
$( "#pg_tasks" ).off("click","a[data-id]").on( "click","a[data-id]", function() {
var p_id = '';
//THE ERROR can be seen here when I use the console
console.log('DATA-ID: '+ $( this ).attr('data-id') );
p_id = $( this ).attr('data-id');
buildTasksDetail(p_id);
});
Event delegation allows the handler to work for matching DOM elements that are added dynamically after the handler is created.