-1

Could anyone explain what are the results of defining event handlers with same signature e.g.:

// event handler 1
$('form.custom select[data-customforms!=disabled]').on('change', function() { 
    console.log('1');
});

// event handler 2
$('form.custom select[data-customforms!=disabled]').on('change', function() { 
    console.log('2');
});

Is it a bad practice? What is the order of execution? Is there any browser specific behavior related to this? Could event handlers in Javascript be extended?

lexeme
  • 2,915
  • 10
  • 60
  • 125

4 Answers4

1

Both handlers will run subsequently. If you name the handlers, rather than making them anonymous, you can destroy them independently (without the need to completely remove all handlers for the 'change' event).

Kippie
  • 3,760
  • 3
  • 23
  • 38
1

The result will be that all the attached events will execute in sequence. This is commonly used to execute multiple functions on a particular event.

In the above case, the first 1 will be logged in console, then 2, just the same order they were applied.

The disadvantage will be that when you remove the change event, all the event handlers attached to that event will be removed (in your case, both the handlers with console.log statement)

You can use event namespacing to overcome this.

Vishal
  • 2,030
  • 22
  • 27
1

JQuery allowing multiple event handler on an element. This means it will not override the older one. I am not sure about the order of execution but it might be random.

alok_dida
  • 1,723
  • 2
  • 17
  • 36
0

JQuery Use bind for set event that mean add to event not replace event for replace you must first delete Event then set.

mohammad mohsenipur
  • 3,218
  • 2
  • 17
  • 22