私の目標は、ページ上の多くの要素にバインドし(on()を使用)、クリックされたら特定の要素からバインドを解除する(off()を使用)ことです。
$(document).on({
mouseenter: enter,
mouseleave: leave,
mousedown: down,
mouseup: up,
click: click
}, ".up_side .thumbsUp");
on()関数は正常に機能していますが、off()を使用してクリックされた要素からバインドを解除する方法がわかりません。
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);
}
ありがとう!!!
解決
.data()を使用してフラグを格納し、コードを実行する前にフラグを確認します。これは回避策のように思われ、コードをより脆弱にします。誰かがより良い方法を見つけたら、投稿してください。ありがとう!
$(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");