2013-05-08 2 views
1

내 사이트의 체크 박스는 각각 이벤트 이름을 나타냅니다.푸시 버튼에 이벤트를 동적으로 바인드 및 바인딩 해제하는 방법

beckboxes의 이벤트베이스에 바인딩하고 바인딩 해제하려면 모든 checkboxex로드 사이트에서 기본적으로 선택되어 있습니다. 이 내 코드입니다 :

var pusher = new Pusher('secret'); 
var channel = pusher.subscribe('latest-news'); 
$("input:checkbox[name=category]:checked").each(function() 
{ 
    channel.bind($(this).val(), function(data) { 
     getNews(data.id); 
    }); 
}); 

function getNews(ids) 
{ 
    $.post("show", {id: ids}) 
      .done(function(data) { 
     $(".c").prepend(data); 
    }); 
} 

이 코드는 체크 박스에 반응 변경 :

$(document).ready(function() { 
    $('input:checkbox[name=category]').click(function() { 
     var $this = $(this); 
     // $this will contain a reference to the checkbox 
     if ($this.is(':checked')) { 
      alert('yes'); 
      channel.bind($(this).val(), function(data) { 
       getNews(data.id); 
      }); 
     } else { 
      alert('no'); 
      channel.unbind($(this).val(), function(data) { 
      }); 
     } 
    }); 
}); 

는 사람이 체크 박스가 다시 무슨 일이 것은 그가 두 번 각 메시지를 얻을 것입니다 확인 취소 할 때 문제가 잘 작동 . 그래서 동일한 이벤트에 대해 두 번 바인드하지 않고 이벤트에 동적으로 바인딩하고 바인드 해제하는 올바른 방법은 무엇입니까? eventNamecallback : 덕분에 당신이 본 것처럼

답변

1

channel.unbind function는 두 개의 매개 변수를 사용합니다. eventName은 문자열이고 callback 매개 변수는 함수 참조입니다. unbind을 호출 할 때 올바른 eventName을 전달할 가능성이 있지만 다른 함수에 대한 참조를 전달하므로 호출이 실패합니다.

$(document).ready(function() { 
    $('input:checkbox[name=category]').click(function() { 
     var $this = $(this); 
     // $this will contain a reference to the checkbox 
     if ($this.is(':checked')) { 
      alert('yes'); 
      channel.bind($(this).val(), handleEvent); 
     } else { 
      alert('no'); 
      channel.unbind($(this).val(), handleEvent); 
     } 
    }); 
}); 

function handleEvent(data) { 
    getNews(data.id); 
} 

참고 :

+0

덕분에이 문제를 해결하려면

당신은 바인딩 해제 바인딩 할 때 참조하고 사용할 수있는 하나의 기능을 /이 있어야 이제 작동합니다. –