logo
down
shadow

When should one event listener be used and when should multiple ones be used?


When should one event listener be used and when should multiple ones be used?

By : braka bos
Date : November 17 2020, 11:58 AM
wish help you to fix your issue I also didn't know which is faster(even if the difference is small).So I wrote the test code
code written by coffeescript
code :
<div id=formContainer>
    <input type="text" id="a">
    <input type="text" id="b">
</div>

counterA = counterB = 0
$("#formContainer").click( (e) ->
  switch $(e.target).attr("id")
    when "a"
      counterA++
    when "b"
      counterB++
)
startTime = new Date()
for i in [0...10000]
  $("#a").trigger("click")
  $("#b").trigger("click")
endTime = new Date() - startTime
console.log("listen to container : #{endTime} ms","counterA is #{counterA}","counterB is #{counterB}")

counterA = counterB = 0
$("#formContainer").off("click")
$("#a").click((e) ->
  counterA++
)
$("#b").click((e) ->
  counterB++
)
startTime = new Date()
for i in [0...10000]
  $("#a").trigger("click")
  $("#b").trigger("click")
endTime = new Date() - startTime
console.log("listen to each elem : #{endTime} ms","counterA is #{counterA}","counterB is #{counterB}")
listen to container : 2224 ms counterA is 10000 counterB is 10000

listen to each elem : 1952 ms counterA is 10000 counterB is 10000
<div id="outer">
  <div id="element1">
    <div class="children1"></div>
    <div class="children2"></div>
  </div>
  <div id="element2">
    <div class="children1"></div>
    <div class="children2"></div>
  </div>
</div>

counterA = counterB = 0

$("#outer").click( (e) ->
  if $(e.target).closest("#element1").length
    counterA++
  else if $(e.target).closest("#element2").length
    counterB++
  else
    console.log("unexpected event")
)
startTime = new Date()
for i in [0...5000]
  $("#element1 .children1").trigger("click")
  $("#element1 .children2").trigger("click")
  $("#element2 .children1").trigger("click")
  $("#element2 .children2").trigger("click")
endTime = new Date() - startTime
console.log("listen to outer : #{endTime} ms",counterA,counterB)

$("#outer").off("click")
counterA = counterB = 0
$("#element1 .children1,#element1 .children2").click( (e) ->
  counterA++
)
$("#element2 .children1,#element2 .children2").click( (e) ->
  counterB++
)
startTime = new Date()
for i in [0...5000]
  $("#element1 .children1").trigger("click")
  $("#element1 .children2").trigger("click")
  $("#element2 .children1").trigger("click")
  $("#element2 .children2").trigger("click")
endTime = new Date() - startTime
console.log("listen to each elem : #{endTime} ms",counterA,counterB)
listen to outer : 2547 ms 10000 10000

listen to each elem : 2159 ms 10000 10000


Share : facebook icon twitter icon
Is it bad practice to use the same event-listener callback for multiple Event types?

Is it bad practice to use the same event-listener callback for multiple Event types?


By : user3784662
Date : March 29 2020, 07:55 AM
hope this fix your issue I think it depends on how many events you have, and how similar their effects are. If both the event types are semantically similar (e.g. MOUSE_DOWN and MOUSE_CLICK) and their effect is similar (e.g. press a button), then you could bundle them.
If the effects of the events are too different (I'd say less than 80% identical code) I would advise against it, then just write multiple handlers and group the common functionality in a separate subroutine.
HTML5 Multiple Canvases event listener - how to determine which canvas experienced the event?

HTML5 Multiple Canvases event listener - how to determine which canvas experienced the event?


By : Akhil Pawa
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , I'm new to JS. I'm not using jQuery, and I have a question. I've created a variable number of canvases on a page, all have an eventlistener like so:
code :
function clickReporter(e){
    console.log( this ); // in a eventListener , this point to the element fire the event
    console.log( e.target ); // in fireFox and webkit, e.target point to the element fire the event
}
Binding a event listener on document vs binding event listener on multiple elements

Binding a event listener on document vs binding event listener on multiple elements


By : lann Yu
Date : March 29 2020, 07:55 AM
may help you . The only difference is the when drag events trigger. When on the element it only triggers if the drag/drop is happening on that element, where as set for the document they are triggered when drag/drop anywhere on the page.
Unless you do some css tricks to show where the drag/drop area is the user might try to drop whatever somewhere else and the event wont ever get triggered.
Event Listener for click event on multiple buttons of same name but different value

Event Listener for click event on multiple buttons of same name but different value


By : Mustafa Karalı
Date : March 29 2020, 07:55 AM
this will help Use document.querySelectorAll() to loop through all the occurences of a button with a name of "button" and addEventListener()s to them. The buttons can have different values, but it checks for the name only:
code :
var linkListener = document.querySelectorAll("button[name='button']");

for (i=0;i<linkListener.length;i++){
  linkListener[i].addEventListener("click", linkFunction);
  }

function linkFunction(){
  
  alert("You clicked a button with a \"name\" of \"button\".");
  
  }
<button name="button">A button</button><button name="button">A button</button><button name="button">A button</button><button name="button">A button</button><button name="button">A button</button><button name="button">A button</button><button name="button">A button</button><br/><br/>

<button name="button1">A button</button><button name="button2">A button</button><button name="button3">A button</button><button name="button4">A button</button><button name="button5">A button</button><button name="button6">A button</button><button name="button7">A button</button>
adding event listener for multiple elements and detecting which element is triggering the event - jQuery

adding event listener for multiple elements and detecting which element is triggering the event - jQuery


By : AndSig
Date : March 29 2020, 07:55 AM
it helps some times You can either use this or check the target property of the passing event of the event handler function:
Using this:
code :
$('#element1, #element2, #element3, #element4').on('click', function(event){
    console.log('The id of the clicked button is: ' +this.id)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="element1">Button1</button>
<button id="element2">Button2</button>
<button id="element3">Button3</button>
<button id="element4">Button4</button>
$('#element1, #element2, #element3, #element4').on('click', function(event){
    console.log('The id of the clicked button is: ' +event.target.id)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="element1">Button1</button>
<button id="element2">Button2</button>
<button id="element3">Button3</button>
<button id="element4">Button4</button>
Related Posts Related Posts :
  • Build Fails: `npm rebuild node-sass --force`
  • Angular Datepicker change dateformat
  • Trying to extract data from between two sets of characters
  • Configuring Jest in WebStorm
  • Uncaught Error: Syntax error, unrecognized expression: tr.ec_portfolio_title,
  • JQuery fading in fading out continuously
  • Unexpected end of input (Line 1) and Undefined Function?
  • How to animate the width of a div slowly with jquery
  • JavaScript + RegEx Complications- Searching Strings Not Containing SubString
  • SignalR - Unable to get property 'client' of undefined or null reference
  • full calendar not displaying when loaded (with backbone)
  • Angular: Update service and share data between controllers
  • ReplaceAll Google script
  • Search for matching LI items in separate UL
  • Access arguments of an... argument
  • Customizing Google custom search jsapi (query strings)
  • React | Can´t load Images > Module not found
  • Dynamically creating buttons in DOJO
  • 404 Not Found in AJAX post call
  • How do I find out, using javascript, what software opened and running my application?
  • Javascript to check the status of wireless connection
  • StarDict support for JavaScript and a Firefox OS App
  • Phonegap event Resume
  • call javascript function on ENTER key press?
  • When is the best time to remove no-js classes from the html tag
  • Recommended email sending languages
  • setInterval not working properly with chrome
  • Does IE create new scope for each script tag?
  • Uncaught SyntaxError: Unexpected token < Underscore and parse issues
  • How to pass captured URL to Email Body in HTML
  • How to structure default nested resources?
  • Store all the keys of a JSON object in a variable
  • Need an efficient way to group the Array of object in javascript
  • a sensible approach to highcharts x-axis labels
  • IDE autocompletion for javascript AMD loading style
  • Bootstrap menu disappears after first click setting the ul style to none
  • split ajax json response errors in each field
  • how to add javascript in head in cmsms
  • REGEX: Finding the correct occurrence order of some given special characters in a string
  • How do you preserve a JavaScript date's time zone from browser to server, and back?
  • Return binary result from phantomjs webserver
  • must be listed in the web_accessible_resources manifest key in order to be loaded by pages outside the extension.
  • Replacing a substring of an element's text with another string
  • How do I filter marks greater than or equal to 90 in this array?
  • Modify the text of my radio input button?
  • Clicking on status bar does not scroll to top of app (Trigger.io)
  • Mocha JS: How to highlight specific assertion failure?
  • $.getJSON jquery parsing to HTML
  • Find items of a certain class (a) that are also in other classes (b,c,d)
  • Setting different images for D3 force-directed layout nodes
  • Integrating Dropzone.js with angular
  • Control sprite animation speed
  • Can only one error / success function be assigned for AngularJS $http promises?
  • Working with math in javascript
  • Django variable isnt recognized by javascript
  • $.when does not work with $.scrollTo plugin
  • How to read local xml file using $.ajax?
  • Manifest is not Valid JSON. What is wrong?
  • AngularJS re-initialise JS after statechange
  • WebRupee is not working
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org