syllepsa
syllepsa

Reputation: 75

Unbinding event from component

I've got a view which contains several textarea components. The question is how to unbind 'click' event from the textarea that was clicked? Only from the particular one.

var StreamView = Backbone.View.extend({

 el: "#stream",

 events: {
 "click textarea" : "addSendCommentButton"
 },

 addSendCommentButton : function(event) {

 this.undelegateEvents();

 }

});

Upvotes: 1

Views: 110

Answers (3)

Jonathan Naguin
Jonathan Naguin

Reputation: 14766

If you want to unbind only a specific event you can use something like this:

addSendCommentButton : function(event) {
   this.$el.off('click.delegateEvents' + this.cid, 'textarea');
}

Backbone attach the events using the jQuery on with a specific namespace delegateEvents plus the cid.


I am afraid that this also unbinds the events from other textareas. This is so because the off method needs the same selector that the passed to on as the jQuery documentation says:

To remove specific delegated event handlers, provide a selector argument. The selector string must exactly match the one passed to .on() when the event handler was attached.


Suggestion

You can have a similar behaviour changing a little your code:

var StreamView = Backbone.View.extend({

 el: "#stream",

 events: {
 "click textarea.unfinished" : "addSendCommentButton"
 },

 addSendCommentButton : function(event) {

    $(event.target).removeClass("unfinished");

 }

});

Use a more specific selector to attach the event and remove that class when the callback is called.

Upvotes: 1

YD1m
YD1m

Reputation: 5895

Check this:

var StreamView = Backbone.View.extend({

     el: "#stream",

     events: {
     "click textarea" : "addSendCommentButton"
     },

     addSendCommentButton : function(e) {
        e.target.removeEventListener('click', 'addSendCommentButton');
     }

    });

Upvotes: 0

Vitalii Petrychuk
Vitalii Petrychuk

Reputation: 14225

YD1m answer is correct but I want to share with you another way how to do this. If you want implement one-time event you can use one jQuery method.

You can do this in two ways:

  1. By overriding delegateEvents method
  2. By attaching event after rendering - this.$('textarea').one('click', _.bind(this. addSendCommentButton, this))

Upvotes: 0

Related Questions