簡體   English   中英

Backbone.js View無法正確取消綁定事件

[英]Backbone.js View can't unbind events properly

我有一些Backbone.js代碼將click事件綁定到一個按鈕,我想在點擊后取消綁定,代碼示例如下:

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

然而unbind不起作用,我嘗試了幾種不同的方式,並在jQuery初始化函數中結束事件,但在Backbone.events模型中沒有。

任何人都知道為什么unbind不工作?

它不起作用的原因是Backbonejs沒有綁定DOM Element .button本身的事件。 它委托這樣的事件:

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

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

你必須像這樣取消事件:

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

(docs: http//api.jquery.com/undelegate

所以你的代碼應該是這樣的:

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

解決此問題的另一種方法(可能是更好的方法)是每次調用cancel函數時創建一個像this.isCancelable這樣的狀態屬性,檢查this.isCancelable是否設置為true,如果是,則繼續執行操作並將this.isCancelable設置為false 。

另一個按鈕可以通過將this.isCancelable設置為true來重新激活取消按鈕,而不綁定/解除對click事件的綁定。

你可以用另一種方式解決

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

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

    do:_.once(function(){
        console.log("do something...");
    })
});
var view = new AppView();

underscore.js一旦函數確保包裝函數只能被調用一次。

假設您要取消所有事件的取消操作,有一種更簡單的方法:

this.undelegateEvents();

我喜歡bradgonesurfing的答案。 但是,當創建View的多個實例時,我遇到了使用_.once方法的問題。 也就是說_.once會限制對該類型的所有對象僅調用一次的函數,即限制是在類級別而不是實例級別。

我這樣處理問題:

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

希望這會對某人有所幫助

你可以簡單地使用object.off ,下面的代碼對我有用

initialize:function () {

    _.bindAll(this, 'render', 'mouseover', 'mouseout', 'delete', 'dropout' , 'unbind_mouseover', 'bind_mouseover');
    .......

},

events: {
    'mouseover': 'mouseover',
    'unbind_mouseover': 'unbind_mouseover',
    'bind_mouseover': 'bind_mouseover',
    .....
},

mouseover: function(){
    $(this.el).addClass('hover');
    this.$('.popout').show();
},

unbind_mouseover: function(){
    console.log('unbind_mouseover');
    $(this.el).off('mouseover');
},
bind_mouseover: function(){
    ........
},

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM