【问题标题】:how to dynamic bind and unbind to event on pusher如何动态绑定和取消绑定到推送器上的事件
【发布时间】:2013-05-08 10:31:23
【问题描述】:

我的网站上有复选框,每个复选框都代表一个事件名称。

i 绑定和取消绑定到基于复选框的事件,在站点加载时,默认情况下会选中所有复选框。 这是我的代码:

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) {
            });
        }
    });
});

它工作正常问题是当有人取消选中复选框然后再次检查发生的情况时,他会收到每条消息两次。 那么动态绑定和取消绑定到事件而不绑定到同一事件两次的正确方法是什么。 谢谢

【问题讨论】:

    标签: jquery pusher


    【解决方案1】:

    如您所见,channel.unbind function 采用两个参数:eventNamecallbackeventName 是一个字符串,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 );
    }
    

    参考资料:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-29
      • 2018-01-15
      • 1970-01-01
      • 1970-01-01
      • 2014-09-04
      • 1970-01-01
      • 1970-01-01
      • 2010-12-20
      相关资源
      最近更新 更多