Reputation: 6213
I'm new in JS and I have some difficulties with the using events.
My problem is that the event is repeated more than once. I use socket.io for my simple game. Here is my code:
socket.on("permit", function(){
$('#attack').on('click', function(){
var id;
$('#game-field').on('click', '.cell', function() {
id = parseInt(this.getAttribute('id'));
$('#game-field').unbind('click');
socket.emit('attack', id); /*when event repeats - that line creates problems like a snowball*/
});
});
});
How can I avoid unnecessary repetitions of events?
Upvotes: 0
Views: 99
Reputation: 9637
Use one selector to bind the event at one time .it ll works only one time
$('#attack').one('click', function(){
// your code
});
$('#game-field').one('click', '.cell', function() {
// your code
});
OR
socket.on("permit", function(){
$('#attack').off('click', attecked);
$('#attack').on('click', attecked);
});
function attecked(){
var id;
$('#game-field').one('click', '.cell', function() { // dont unbind the event removed ur code $('#game-field').unbind('click');
id = parseInt(this.getAttribute('id'));
socket.emit('attack', id); /*when event repeats - that line creates problems like a snowball*/
});
}
Upvotes: 1