Backbone.js的视图不能解除绑定正确的事件 [英] Backbone.js View can't unbind events properly

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

问题描述

我有一个click事件绑定到一个按钮Backbone.js的一些code,
我想解除后点击,code样品如下:

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.

任何人都知道为什么取消绑定不工作?

Anyone know why the unbind is not working?

推荐答案

它不工作的原因是Backbonejs不会对DOM元素绑定事件.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

您必须undelegate事件是这​​样的:

You have to undelegate the event like this:

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

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

所以你的code应该是这样的:

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 现在每次在取消函数被调用你检查 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 来真不绑定/解除绑定click事件激活取消按钮。

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

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

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