I have a variable mutedUser which I would like to have persist to another function. I am having a bit of trouble with the variable persisting outside the click event. What would be the best way to have it so the “return mutedUser” would keep the “muted” string addition based on the conditions of the if statement being met? Thanks!
*The console.log’s were me checking to see where the persistance stops
this.isUserMuted = function isUserMuted(payload) {
var mutedUser = '';
// If mute button is clicked place them into muted users list
// check for duplicates in list
$("#messages-wrapper").off('click', '.message button.muteButton');
$("#messages-wrapper").on('click', '.message button.muteButton', function(e) {
$('#unMute').show();
//create userId reference variable
var chatUserID = parseInt($(this).parent().parent().attr("data-type"));
//store userId in muted user object
mutedUsers[chatUserID] = {};
mutedUsers[chatUserID].id = chatUserID;
mutedUsers[chatUserID].muted = true;
if (mutedUsers[chatUserID] !== null && mutedUsers[chatUserID].id === payload.a) {
console.log("user is now muted");
mutedUser += ' muted';
console.log(mutedUser + 1);
}
console.log(mutedUser + 2);
});
return mutedUser;
};
If I understood what you’re trying to do (by looking at the code), this would be the best approach:
The code retains the array of
mutedUsers, andisUserMutedfunction checks if provided user is in that array. In the code you provided, you would attach a new event handler every timeisUserMutedfunction is called..The
isUserMutedfunction could even be shortened to: