javascript question - using for loop for dynamic event listeners creates multiple event listeners
Posted: 10 March 2022, 02:32
Thanks for any advice and insight
I get multiple event listeners when I use the for loop to dynamic node ids.
How would you add event listeners to dynamically created nodes using the for loop?
Why are multiple event listeners created for each node id when I use any for loop?
Here is my example code
I have tried using a forEach loop and had the same results - multiple event listeners for each node id
manually listing each one works well though - I get 1 and only 1 event listener for each node.
Thanks
I get multiple event listeners when I use the for loop to dynamic node ids.
How would you add event listeners to dynamically created nodes using the for loop?
Why are multiple event listeners created for each node id when I use any for loop?
Here is my example code
Code: Select all
for( var player_id in gamedatas.players ){
this.num_players++;
let room_id = "#bottom_card" + this.num_players.toString();
dojo.connect( $('room_id'), 'onclick', this, 'onRoomSelect' );
}
Code: Select all
for( var player_id in gamedatas.players ){
this.num_players++;
let room_id = "#bottom_card" + this.num_players.toString();
dojo.connect( $('room_id'), 'onclick', this, 'onRoomSelect' );
this.selectables.push(room_id);
}
this.selectables.forEach( node_id => dojo.connect( $( node_id ), 'onclick', this, 'onRoomSelect' ));
Code: Select all
dojo.connect( $('bottom_card1'), 'onclick', this, 'onRoomSelect' );
dojo.connect( $('bottom_card2'), 'onclick', this, 'onRoomSelect' );
dojo.connect( $('bottom_card3'), 'onclick', this, 'onRoomSelect' );
dojo.connect( $('bottom_card4'), 'onclick', this, 'onRoomSelect' );