Failed to delete one of several event listeners in Backbone.js view.

I am trying to remove an event listener from a specific DOM element and have problems. Below are the parts of the code I'm playing with:

Search.Views.MainSearch = Backbone.View.extend({
    // initialization function
    events: {
        'click #search-submit' : 'searchSubmit',
        'click #some-button': 'disableSearch',
        'click #some-other-button': 'someFunction'
    }|,
    disableSearch: function(){
        // this statement works, but it removes all listeners
        $(this.el).off('click');
        // this statement doesn't work
        // $('#search-submit').off('click', this.searchSubmit);
        // This also doesn't work
        // $(this.el).off('click', this.searchSubmit);
    }

Clicking the # search-submit button works as expected. Clicking the # some-button button works because it calls the disableSearch method. However, I cannot remove only the click event from the # search-submit button. I can remove all listeners, but this is not suitable for my purpose, because it removes the listener from # some-other-button.

Is there a way to remove only event listeners that excite me and leave them intact? Is there a better way to hook event listeners first? Thanks...

+4
1

, :

this.$el.off('click', '#search-submit');

http://jsfiddle.net/nikoshr/fS278/

(Backbone , this). search-submit :

var V = Backbone.View.extend({
    events: {
        'click #some-button': 'disableSearch',
        'click #some-other-button': 'someFunction'
    },

    initialize: function () {
        // let make sure searchSubmit has the view as context
        _.bindAll(this, 'searchSubmit');
        // and then direct the event to the bound function
        this.$el.on('click', '#search-submit', this.searchSubmit);
    },

    disableSearch: function(){
        // this.searchSubmit is the same function as in initialize
        // it can be detached
        this.$el.off('click', this.searchSubmit);
        return false;
    },

    searchSubmit: function() {
        console.log('searchSubmit');
        return false;
    }
});

http://jsfiddle.net/nikoshr/fS278/1/

+1

Source: https://habr.com/ru/post/1524322/


All Articles