Louys Patrice Bessette Louys Patrice Bessette - 15 days ago 5
jQuery Question

jQuery .on() shortcut syntax vs delegation

This one is about a coding syntax ( a shortcut? ) that I just found.

I really got mystified with this

syntax last week.



The main use I was doing of
.on()
, until now, was to delegate event(s) on dynamically added elements.


Like so:


$("[selector]").on("[event,event,event,...]","[delegate selector]",function(){
//... Something.
});


This is a common use to bind ONE handler from a collection to another (dynamic child) regarding one or many events.






But, now that I know about the existance of this
.on()
syntax
...

Which is more "event-specific" and really allows to be more concise in code writing:


$("[selector]").on({
[event]:function(){
//...Something
},
[event]:function(){
//...Something else.
}
});


I see this (new for me!) syntax as providing an object as argument to
.on()
.

Even many objects, coma separated.


It is wonderfully binding specific handlers to a collection, regarding numerous events.

I think it's a real efficient way to code... And readability is great.

But now...



How to delegate the events from an "onloaded" selector to a dynamically appended child using this syntax?

Is it possible ?

Please, tell me yes and show me how!

Answer

How to delegate the events from an "onloaded" selector to a dynamically appended child using this syntax?

The syntax you are looking for is this:

$('staticParentElement').on({
    [event]:function(){
        //...Something
    },
    [event]:function(){
        //...Something else.
    }
}, 'dynamicDescendants');