Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 210
Randomblue Avatar asked Dec 06 '25 02:12

Randomblue


1 Answers

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.

like image 94
Rory McCrossan Avatar answered Dec 07 '25 19:12

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!