Martin Mazza Dawson Martin Mazza Dawson - 7 months ago 17
Javascript Question

jQuery Pass object through .On() without event properties

How do I pass the object

self
to the function on the 'Click' event? At the moment it is passing
jQuery.Event
object which contains a
data
property with my object, but I want the object to be
jPlayer
, not
jQuery.Event


The reason I want this is that when the function is called on the event the code won't work because I would have to access the data through jPlayer.data.jPlayer, if I do this then my
changeShuffleIcon(self);
won't work.

ready: function() {
var self = this;
changeShuffleIcon(self);

$(".jp-shuffle").on("click", { jPlayer: self }, changeShuffleIcon);
}


...

function changeShuffleIcon(jPlayer) {
if ($(jPlayer).hasClass("jp-state-shuffled")) {
$(".jp-shuffle").children().addClass("clicked-button");
} else {
$(".jp-shuffle").children().removeClass("clicked-button");
}
}


(Cut some code out for brevity.)

Answer

You could do something like this:

function changeShuffleIcon(jPlayer, isNotEvent)
{
    if(!isNotEvent)
    {
        jPlayer = jPlayer.data.jPlayer;
    }
    if ($(jPlayer).hasClass("jp-state-shuffled")) {
        $(".jp-shuffle").children().addClass("clicked-button");
    } else {
        $(".jp-shuffle").children().removeClass("clicked-button");
    }
}

ready: function() {
    var self = this;
    changeShuffleIcon(self, true);

    $(".jp-shuffle").on("click", { jPlayer: self }, changeShuffleIcon);
}
Comments