Reputation: 75
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
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.
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
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
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:
delegateEvents
methodthis.$('textarea').one('click', _.bind(this. addSendCommentButton, this))
Upvotes: 0