Backbone.js View 无法正确解绑事件 [英] Backbone.js View can't unbind events properly

查看:16
本文介绍了Backbone.js View 无法正确解绑事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些将点击事件绑定到按钮的 Backbone.js 代码,我想在点击后解除绑定,代码示例如下:

I have some Backbone.js code that bind a click event to a button, and I want to unbind it after clicked, the code sample as below:

var AppView = Backbone.View.extend({
    el:$("#app-view"),
    initialize:function(){
        _.bindAll(this,"cancel");
    },

    events:{
        "click .button":"cancel"
    },

    cancel:function(){
        console.log("do something...");
        this.$(".button").unbind("click");
    }
});
var view = new AppView();

然而,解除绑定不起作用,我尝试了几种不同的方法,最终在使用 jQuery 的初始化函数中绑定事件,而不是在 Backbone.events 模型中.

However the unbind is not working, I tried several different way and end up binding event in initialize function with jQuery but not in Backbone.events model.

有人知道为什么 unbind 不起作用吗?

Anyone know why the unbind is not working?

推荐答案

它不起作用的原因是 Backbonejs 没有绑定 DOM Element .button 本身的事件.它像这样委托事件:

The reason it doesn't work is that Backbonejs doesn't bind the event on the DOM Element .button itself. It delegates the event like this:

$(this.el).delegate('.button', 'click', yourCallback);

(文档:http://api.jquery.com/delegate)

你必须像这样取消委托:

You have to undelegate the event like this:

$(this.el).undelegate('.button', 'click');

(文档:http://api.jquery.com/undelegate)

所以你的代码应该是这样的:

So your code should look like:

var AppView = Backbone.View.extend({
    el:$("#app-view"),
    initialize:function(){
        _.bindAll(this,"cancel");
    },

    events:{
        "click .button":"cancel"
    },

    cancel:function(){
        console.log("do something...");
        $(this.el).undelegate('.button', 'click');
    }
});
var view = new AppView();

解决这个问题的另一种(也许更好)的方法是创建一个像 this.isCancelable 这样的状态属性,现在每次调用 cancel 函数时,你检查是否 this.isCancelable 设置为 true,如果是,则继续您的操作并将 this.isCancelable 设置为 false.

Another (maybe better) way to solve this is to create a state attribute like this.isCancelable now everytime the cancel function is called you check if this.isCancelable is set to true, if yes you proceed your action and set this.isCancelable to false.

另一个按钮可以通过将 this.isCancelable 设置为 true 来重新激活取消按钮,而无需绑定/取消绑定点击事件.

Another button could reactivate the cancel button by setting this.isCancelable to true without binding/unbinding the click event.

这篇关于Backbone.js View 无法正确解绑事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆