Randomblue Randomblue - 4 months ago 15
jQuery Question

DRYing up event handlers

I have a modal with three buttons: close, remove and save. Each button requires a click handler, and each click handler hides the modal as its last action. This is the naive approach:

// Close
$('#edit-user-close').on('click', function () {
$modal.modal('hide');
});

// Remove
$('#edit-user-remove').on('click', function () {
removeUser();

$modal.modal('hide');
});

// Save
$('#edit-user-save').on('click', function () {
saveChanges();

$modal.modal('hide');
});


This code feels very much like it could be DRYed up. What techniques/syntax could I use to DRY up those event handlers?

Answer Source

The code itself seems fine to me. If you wanted to do it under one click handler you could use a class with a data attribute to determine the action, try this:

<a href="#" class="modal-action" data-action="close">Close/a>
<a href="#" class="modal-action" data-action="remove">Remove user</a>
<a href="#" class="modal-action" data-action="save">Save</a>
$('.modal-action').click(function() {
    switch ($(this).data('action')) {
       case 'remove':
           removeUser();
           break;
       case 'save':
           saveChanges();
           break;
    }

    $modal.modal('hide');
});

If you're only ever going to have 2 buttons (besides close) then the switch could be shortened to an if statement. I used a switch as it's more extensible, should you need to add different button actions in future.