My goal is to bind to many elements on page (using on()) and then to unbind from a specific element (using off()) once it has been clicked.
$(document).on({
mouseenter: enter,
mouseleave: leave,
mousedown: down,
mouseup: up,
click: click
}, ".up_side .thumbsUp");
The on() function is working well, but I can’t figure out how to use off() to unbind from the clicked element.
var click = function() {
var thumbsUp = $(this);
var successCallback = function(data) {
// This is where I need to unbind the clicked element
$(thumbsUp).off({
mouseenter: enter,
mouseleave: leave
});
}
$(this).castVote(direction, modelName, modelId, successCallback, errorCallback);
}
Thanks!!!
Solution
Use .data() to store a flag and check the flag before executing code. This does seems like a workaround and makes the code more brittle. If anyone finds a better way, please post back. Thanks!
$(document).on({
mouseenter: function(){
if ($(this).data("submitted") != true)
{
$(this).css("cursor", "pointer");
$(this).css("backgroundPosition", "-48px");
}
},
mouseleave: function(){
if ($(this).data("submitted") != true)
{
$(this).css("backgroundPosition", "0px");
}
},
mousedown: function() {
if ($(this).data("submitted") != true)
{
$(this).css("backgroundPosition", "-96px");
}
},
mouseup: function() {
if ($(this).data("submitted") != true)
{
$(this).css("backgroundPosition", "0px");
}
},
click: function() {
if ($(this).data("submitted") != true)
{
var thumbsUp = $(this);
var ballotBox = $(thumbsUp).parent();
var votingStation = $(ballotBox).parent();
//ballotBox.hide(0, "", function() {
var direction = $(thumbsUp).dataset("direction");
var modelName = $(votingStation).dataset("modelName");
var modelId = $(votingStation).dataset("modelId");
var successCallback = function(data) {
$(thumbsUp).css("backgroundPosition", "-144px");
// Add flag to indicate successful vote
thumbsUp.data("submitted", true)
$(this).vote_up_side('animateBallotBox', data, ballotBox, thumbsUp);
}
var errorCallback = function(XMLHttpRequest, textStatus, errorThrown) {
$(this).vote_up_side('animateError', ballotBox);
}
$(this).castVote(direction, modelName, modelId, successCallback, errorCallback);
}
}
}, ".up_side .thumbsUp");
The
.off()documentation says:and (my emphasis)
Hence it’s not possible AFAIK to selectively (no pun intended) remove some elements from a delegated event handler.
I think your only option is to leave the event handler in place, but tag each element with some
.data()which you use to indicate whether that particular element has already been clicked.