How to avoid 'double' event double binding?

78 Views Asked by At

I've got a page containing numerous links that will trigger a cjuidialog to open:

<?php foreach($client->assignments as $clientProjects) { ?>
    [...]
    <a href="javascript:void(0);"
        id="attach_file_project_<?=$clientProjects['project_id']?>"
        class="attach_timesheet_file"
        data-id="<?=$clientProjects['project_id']?>"
        data-week-start="<?=$client->clientWeek[0]?>"
        data-week-end="<?=$client->clientWeek[6]?>"
    >Attach File</a>
    [...]
<?php } ?>

This is the script that will trigger the dialog. The dialog content is being generated in the ajax call:

$(".attach_timesheet_file").off('click').on("click", function(e) {
    e.preventDefault();
    $('#files-grid .delete').off('click');
    var id = $(this).data("id");
    var weekStart = $(this).data("week-start");
    var weekEnd = $(this).data("week-end");
    var url = "<?=Yii::app()->createUrl('admin/timesheetNew/attachTimesheet')?>";
    $.ajax({
        type: 'GET',
        url:url + "?id=" + id + "&week_start=" + weekStart + "&week_end=" + weekEnd,
        success: function(data) {
            var modal = $("#attachFileModal");
            modal.html(data);
            modal.dialog('open');
            return true;
        }
    })
});

The dialog allows you to add & delete files. Inside the dialog, I'm using a CGridView widget which will include a delete link:

$this->widget('zii.widgets.grid.CGridView', [
    'id' => 'files-grid',
    'dataProvider' => $dataProvider,
    'columns' => [
        [...]
        [
            'class' => 'CButtonColumn',
            'template' => '{delete}',
            'buttons' => [
                'delete' => [
                    'label' => 'Delete',
                    'imageUrl' => null,
                    'url' => 'Yii::app()->createUrl("admin/timesheetNew/deleteFile", ["id" => $data["id"]])'
                ]
            ],
            'deleteConfirmation' => 'Are you sure you want to delete this file?',
            'afterDelete' => 'function(){
                $("#files-grid").yiiGridView("update");
            }'
        ]
    ]
]);

The problem I'm facing is when I open, close and re-open a dialog, and I wish to delete a file, I need to click the confirm button as many times as I opened a dialog.

I tried with $(".attach_timesheet_file").off('click'), which should work to unbind the event, but it didn't help, also trying the same for #files-grid .delete didn't work as well.

Has anyone got an idea?

1

There are 1 best solutions below

0
On

My approach is "tag" the new binding with a unique class. I already think about using some dataset property but adding a unique class looks easier to use. By the way, the problem about use "off('click')" is that you unbind any other click that you already have;

$('#filtro').not('.bindfiltro').change(function () {
    $(this).submit();
}).addClass('bindfiltro');