Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to better handle events

If I have multiple events on an element I am currently handling those events as written here:

$("body").on("click", ".element", function(e) {
    // Do something on click
});

$("body").on("change", ".element", function(e) {
    // Do something on change
});

Is there a way to combine all the events on an element in one on() call? What is the best practice if there are multiple events associated with one element?

$("body").on("change click", ".element", function(e) {
    // Can I detect here if it was change or click event and perform an action accordingly?
});
like image 547
A Patel Avatar asked Apr 22 '15 10:04

A Patel


People also ask

What are the 5 C's of event management?

The process of planning an event from start to finish may be divided into 5 basic phases, which we have called the 5 Cs. These are Concept, Coordination, Control, Culmination and Closeout.

What are the 7 key elements of event management?

Event management has 7 key elements: event infrastructure, audience, attendees, organizers, venue, and media. Your event software should be able to manage all of these elements.


2 Answers

You can use the type property of the event to determine which logic to execute:

$('body').on('change click', '.element', function(e) {
    if (e.type == 'click') {
        // do something...
    } 
    else if (e.type == 'change') {  
        // do something else...
    }
});

Alternatively you can provide an object to on which contains the functions to bind with the event type names as the keys:

$('body').on({
    click: function() {
        // do something on click...
    },
    change: function() {
        // do something on change...
    }
}, '.element');

Personally I would use the latter method. The whole point of having a unified on() handler is negated when using a rather ugly if statement to split the event types.

like image 123
Rory McCrossan Avatar answered Sep 29 '22 09:09

Rory McCrossan


Yes! jQuery passes the event object which contain the event information:

$("body").on("change click", ".element", function(e) {
    console.log(e.type);
});
like image 43
Sumit Avatar answered Sep 29 '22 11:09

Sumit