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.

FishBasketGordo
  • 22,904
  • 4
  • 58
  • 91
KoU_warch
  • 2,160
  • 1
  • 25
  • 46

3 Answers3

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.

Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
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.

Faust
  • 15,130
  • 9
  • 54
  • 111
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.

Christoph
  • 50,121
  • 21
  • 99
  • 128