Reputation: 1152
So right now, I am using hammer.js to bind some touch controls to an element on the page. By swiping to the right on an element, it will add the class of disabled. If any item has a class of disabled, I want to, essentially, "unbind" the doubletap and the swiperight events ONLY for that element that has the class disabled. Does anyone know if this is possible?
$('.row').hammer({
prevent_default: false,
drag_vertical: false
}).bind('doubletap swiperight', function(e) {
var $this = $(this)
if (e.type == "doubletap") {
confirm("Do You Want To Edit Med?")
}
else if (e.type == "swiperight") {
$this.removeClass('yHighlight');
$this.addClass('gHighlight disabled');
$this.css('opacity','.5')
}
});
Upvotes: 0
Views: 3580
Reputation: 3619
I'd suggest using jQuery event delegation, which is build into the .on()
method. Use the .on()
method instead of .bind()
. Here's an example, which assumes that the rows' parent element has an id of "rowparent".
('.row').hammer({
prevent_default: false,
drag_vertical: false
});
$('#rowparent').on('doubletap swiperight', '.row:not(.disabled)', function(e) {
var $this = $(this)
if (e.type == "doubletap") {
confirm("Do You Want To Edit Med?")
}
else if (e.type == "swiperight") {
$this.removeClass('yHighlight');
$this.addClass('gHighlight disabled');
$this.css('opacity','.5')
}
});
The .on
method takes an optional selector argument. When the doubletap or swiperight events bubble up to #rowparent
, jQuery tests the event's target element against that selector. So this will automagically "unbind" the events, because they stop matching that selector!
If you have a lot of rows, I would call this superior to the other answers that test against the classname in the handler; it's more efficient to only bind a single event handler. However, if you only have a very few rows, it might be more efficient to just check with .hasClass
in the method body, since the :not()
selector is a bit heavy.
Upvotes: 1
Reputation: 437774
You can simply check from inside your event handler if the element that triggered the event has that class; if it does, then return without doing anything.
.bind('doubletap swiperight', function(e) {
var $this = $(this);
// ADDED CODE
if ($this.hasClass("disabled")) {
e.stopPropagation();
return;
}
if (e.type == "doubletap") {
confirm("Do You Want To Edit Med?")
}
else if (e.type == "swiperight") {
$this.removeClass('yHighlight');
$this.addClass('gHighlight disabled');
$this.css('opacity','.5')
}
});
Upvotes: 1