javascript question - for loop and event listeners
Posted: 10 March 2022, 02:25
Thanks for any advice and insight
I get multiple event listeners when I add event listeners to dynamically created node ids with the for loop.
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
manually listing each one works well though - I get 1 event listener for each node.
Thanks
I get multiple event listeners when I add event listeners to dynamically created node ids with the for loop.
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' );