Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with Javascript Variable Scope

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;
};
like image 358
Yasir Avatar asked Dec 20 '12 20:12

Yasir


People also ask

What is the incorrect scope of variable in JavaScript?

Any variable that you declare inside a function is said to have Local Scope. You can access a local variable can within a function. If you try to access any variable defined inside a function from outside or another function, it throws an error.

What are the scope problems caused by VAR?

Variables declared with var will be auto-initialized to undefined within their scope, even if you reference them before they're declared. The big problem is that undefined doesn't always mean you're using a variable before it's defined.

What is the scope of a variable in JavaScript?

The scope of a variable is the region of your program in which it is defined. JavaScript variables have only two scopes. Global Variables − A global variable has global scope which means it can be defined anywhere in your JavaScript code.

What are the problems with global variables in JavaScript?

This is because global variables are easily overwritten by other scripts. Global Variables are not bad and not even a security concern, but it shouldn't overwrite values of another variable. On the usage of more global variables in our code, it may lead to a maintenance issue.


2 Answers

If I understood what you're trying to do (by looking at the code), this would be the best approach:

// 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;
});

this.isUserMuted = function isUserMuted(payload) {
  var mutedUser = '';

  if (mutedUsers[payload.a] !== null) {
      mutedUser += ' muted';
  }

  return mutedUser;
};

The code retains the array of mutedUsers, and isUserMuted function checks if provided user is in that array. In the code you provided, you would attach a new event handler every time isUserMuted function is called..

The isUserMuted function could even be shortened to:

this.isUserMuted = function isUserMuted(payload) {
  return mutedUsers[payload.a] !== null ? ' muted' : '';
};
like image 94
Ivan Ferić Avatar answered Oct 27 '22 00:10

Ivan Ferić


Edit

Sorry, my mistake. Another way is to pass in that variable, i.e.

this.isUserMuted = function isUserMuted(payload, isMuted) {
  isMuted = '';
  // 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");
          isMuted += ' muted';
          console.log(mutedUser + 1);
      }
      console.log(mutedUser + 2);
  });
  return isMuted;
};
like image 22
redconservatory Avatar answered Oct 27 '22 00:10

redconservatory