2014-05-21 111 views
0

我是JS新手,在使用事件方面遇到一些困难。
我的问题是,该事件不止一次重复。我为我的简单游戏使用socket.io。这是我的代码:如何避免重复的JavaScript事件?

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*/ 
     }); 
    }); 
}); 

我该如何避免不必要的事件重复?

+0

PLS份额的jsfiddle此 –

回答

1

使用one选择在同一时间。它LL绑定事件只能一次

$('#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*/ 
     }); 
} 
+0

(T_T)我花了这么多时间今天通过与这个bug战斗...第一种变体工作正常。我之前阅读过有关'one()'的内容,但并未猜到要使用这个:(如此愚蠢......谢谢 – Alendorff