jQuery .on() instead of .delegate() without event
Asked Answered
L

3

8

Is it possible to use jquery .on() method instead of .delegate() when there is no event to be listened to?

According to the .on() documentation:

.on( events [, selector] [, data] , handler(eventObject) )

The events argument is not optional.

The use of .on()/.delegate() is for elements that are added dynamically.

Logrolling answered 9/8, 2012 at 14:32 Comment(7)
What is the purpose of using on or delegate without an event?Bullnose
@Bullnose As of jQuery 1.7, .delegate() has been superseded by the .on() method Jquery Docs for .delegate()Logrolling
Maybe I'm mistaken, but doesn't delegate require an event as well?Bullnose
I'm pretty sure delegate requires an eventFiertz
Totally true, there is no point on using delegate or on if there is not a event attached. ~Genius~ sorry all.Logrolling
well, the question is - what were you trying to do with it? Perhaps it's just a problem of understanding how to solve this initial problem?Foxing
@Foxing the feature is needed to customize an eventsink without modifying jquery source code.Alyse
F
0

Since .on()s purpose it to attach event-handlers to a certain element, it makes absolutely no sense to use it without an event. That's why the event parameter is required.

From the doc:

Description: Attach an event handler function for one or more events to the selected elements.

Foxing answered 9/8, 2012 at 14:47 Comment(0)
F
8

You can use custom events:(it IS still an event, but YOUR event )

markup:

<div id='mePlease'>
 <div id='noWay'>Hi</div>
</div>

$('#mePlease').on('wacky','#noWay',function(){
   alert('wackyEnough');
});
$('#noWay').trigger('wacky');

but really, this could be done with a simple function call.

Fowle answered 9/8, 2012 at 14:51 Comment(0)
C
6

The purpose of these functions is to delegate functionality to events; so no, you can't omit the events parameter from either of these function calls.

I suspect what you want is to "do stuff" to some elements that are loaded after page-load (asynchronously), no? Maybe you also need to do this stuff to elements that already exist on page-load?

In that case I suggest you wrap your declarations in a function, and call that function both on page-load and once the asynchronous call is complete.

Cerography answered 9/8, 2012 at 14:46 Comment(0)
F
0

Since .on()s purpose it to attach event-handlers to a certain element, it makes absolutely no sense to use it without an event. That's why the event parameter is required.

From the doc:

Description: Attach an event handler function for one or more events to the selected elements.

Foxing answered 9/8, 2012 at 14:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.