Backbone.js View can't unbind events properly

前端 未结 5 1936
执笔经年
执笔经年 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:13

    I like bradgonesurfing answer. However I came across a problem using the _.once approach when multiple instances of the View are created. Namely that _.once would restrict the function to be called only once for all objects of that type i.e. the restriction was at the class level rather than instance level.

    I handled the problem this way:

    App.Views.MyListItem = Backbone.View.extend({
      events: {
        'click a.delete' : 'onDelete'
      },
    
      initialize: function() {
        _.bindAll(this);
        this.deleteMe = _.once(this.triggerDelete);
      },
    
      // can only be called once
      triggerDelete: function() {
        console.log("triggerDelete");
        // do stuff
      },
    
      onDelete:(function (e) {
        e.preventDefault();
        this.deleteMe();
      })
    });
    

    Hopefully this will help someone

提交回复
热议问题