Backbone.js View can't unbind events properly

前端 未结 5 1937
执笔经年
执笔经年 2020-12-25 08:11

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.Vie         


        
5条回答
  •  爱一瞬间的悲伤
    2020-12-25 09:07

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

    (docs: http://api.jquery.com/delegate)

    You have to undelegate the event like this:

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

    (docs: 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();
    

    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.

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

提交回复
热议问题