I originally had this function to remove an item when the delete-item
button is clicked:
$( document ).on( "click", ".delete-item", function() {
console.log("Removing "+$(this).data('id'));
var id=$(this).data('id');
var parent=$(this).parent().parent().parent();
parent.remove();
$(".subitem-row"+id).remove();
applyCartChanges();
});
It works fine. But when I try to do a dialog (using OnsenUI and PhoneGap) to confirm it first before removing, like this:
$( document ).on( "click", ".delete-item", function() {
ons.notification.confirm({
message: getTrans('Remove from cart?','remove_from_cart') ,
title: dialog_title_default ,
buttonLabels: [ getTrans('Yes','yes') , getTrans('No','no') ],
animation: 'default', // or 'none'
primaryButtonIndex: 1,
cancelable: true,
callback: function(index) {
if (index==0){
console.log("Removing "+$(this).data('id'));
var id=$(this).data('id');
var parent=$(this).parent().parent().parent();
parent.remove();
$(".subitem-row"+id).remove();
applyCartChanges();
}
}
});
});
Then it suddenly doesn't work anymore :( In the console, it says undefined
for the $(this).data('id')
. Any ideas why?
This is because the reference to this
is not obtained as a clicked element inside the dialog. So, rewrite your code as
$( document ).on( "click", ".delete-item", function() {
var _this = this;
ons.notification.confirm({
message: getTrans('Remove from cart?','remove_from_cart') ,
title: dialog_title_default ,
buttonLabels: [ getTrans('Yes','yes') , getTrans('No','no') ],
animation: 'default', // or 'none'
primaryButtonIndex: 1,
cancelable: true,
callback: function(index) {
if (index==0){
console.log("Removing "+$(_this).data('id'));
var id=$(_this).data('id');
var parent=$(_this).parent().parent().parent();
parent.remove();
$(".subitem-row"+id).remove();
applyCartChanges();
}
}
});
});
Notice that i have taken the reference of this
inside a new variable _this
so it will be accessible inside the dialog.