aman704
aman704

Reputation: 76

Replace multiple jQuery .on() with one

I have a dynamic plugin with various functions and I'm triggering those functions with click events.

My HTML:

<div class="container">
    <div class="el" id="el1">
        <a href="#" class="edit-el">Edit</el>
        <a href="#" class="delete-el">Delete</el>
    </div>
</div>

This is my javascript:

// Edit an el
$('.container').on('click', '.edit-el', function(e){
    var elId = $(e.currentTarget).closest('.el')[0];
    plugin.editEl(elId);
});
// Delete an el
$('.container').on('click', '.delete-el', function(e){
    var elId = $(e.currentTarget).closest('.el')[0];
    plugin.deleteEl(elId);
});

Question: Is it possible to optimize this code so I don't have two click event listeners? This should give an idea of what I'm trying to achieve (Not working):

$('.container').on('click', function(e){
    var control = e.currentTarget;
    if ( control == '.edit-el') {
        plugin.editEl(elId);
    }
    if ( control == '.delete-el') {
        plugin.deleteEl(elId);
    }
});

Upvotes: 0

Views: 64

Answers (3)

Adrian Wragg
Adrian Wragg

Reputation: 7401

I'm not going to answer this question with optimised code, simply because I think the code you have is already optimal. The reason is down to a simple phrase - separation of concerns. From Wikipedia:

In computer science, separation of concerns (SoC) is a design principle for separating a computer program into distinct sections, such that each section addresses a separate concern.

At present, you have two completely separate areas of functionality:

  • An event handler that manages editing of an element
  • An event handler that manages deletion of an element

The "benefit" you would get from having both under the same handler is that your code will be slightly shorter. In return, you'd be combining two completely distinct functions into a single procedure and impacting on both readability and maintainability.

Upvotes: 2

Suren Srapyan
Suren Srapyan

Reputation: 68635

Try this code. Get the target element an compare it's href

$('.container').on('click', function(e){
    var control = $(e.target);
    if ( control.hasClass('edit-el')) {
        plugin.editEl(elId);
    }
    else if ( control.hasClass('delete-el')) {
        plugin.deleteEl(elId);
    }
});

Upvotes: 2

Satpal
Satpal

Reputation: 133403

You can use .is()

$('.container').on('click', function(e){
    var control = $(e.target);
    if ( control.is('.edit-el')) {
        plugin.editEl(elId);
    }
    else if ( control.is('.delete-el')) {
        plugin.deleteEl(elId);
    }
});

However I would recommend you to persist with your existing approach due to separation of concerns principle

Upvotes: 2

Related Questions