Scope problems in eventHandler

javascript event handler variable scope
javascript this scope
addeventlistener multiple events
nested scope javascript
javascript rest listener
dom events
addeventlistener bind
common challenges with javascript

So javascript isn't really my forte. I'm putting a simple click event handler on some elements and it works fine if I manually attach the handler on each element that needs it like so:

$('#box-content-fr-tab').click(function () {
    switchLang('menu', 'fr');
});

$('#box-content-nl-tab').click(function () {
     switchLang('menu', 'nl');
});

//etc

function switchLang(currentField, currentLang){
    $('#box-'+currentField+'-'+currentLang+'-tab').addClass('active');
    $('#box-'+currentField+'-'+currentLang).addClass('active show');

    for(oLang in $.object.langues){
        if(oLang !== currentLang && oLang !== 'end'){
            $('#box-'+currentField+'-'+oLang+'-tab').removeClass('active');
     $('#box-'+currentField+'-'+oLang).removeClass('active show');
        }
    }
}

I'd like to not manually attach the onClick handler on each element but when I naively try to loop through a list, I run into scope problems with my currentLang and currentField variables. I tried something like:

for(lang in this.langues){
    if(lang !== 'end'){
       var currentLang = lang;
        $('#box-content-'+lang+'-tab').click(function(){
            switchLang(currentField, currentLang);
        });
    }
}

but it's not working. Any ideas on how to make it more dynamic?

I'd use something like this, it should work fine since lang is just a string as I understand but you should remember that let is not supported in some old browsers:

for(let lang in this.langues){
    if(lang !== 'end'){
        $('#box-content-'+lang+'-tab').click(function(){
            switchLang(currentField, lang);
        });
    }
}

If you're trying to iterate until the end of the array/object, you don't even need to check for lang !== 'end', Hence:


for(let lang in this.langues){
    $('#box-content-'+lang+'-tab').click(function(){
        switchLang(currentField, lang);
    });
}

Scope problems in eventHandler, I'd use something like this, it should work fine since lang is just a string as I understand but you should remember that let is not supported in some old browsers: Help with Event Handlers with Scope 541881 May 24, 2007 1:33 AM I have a question of how I must implement the event handlers with scope, I have problems in the execution of processes BPEL (they are generating exceptions in the dehydration) I have two models for event handlers and I need to know which is the best way to implement event handlers.

As others stated, you can use let keyword, in your case you don't even need the variable unless you need some processing done on it.


this.langues.forEach((lang) => {
  if (lang !== 'end') {
    $('#box-content-' + lang + '-tab').click(() => {
      switchLang(currentField, lang);
    });
  }
});

Else, if you're iterating until the end of the array, you don't need to check for 'end' unless you need it for something else, Hence:


this.langues.forEach((lang) => {
    $('#box-content-'+lang+'-tab').click(function(){
        switchLang(currentField, lang);
    });
)};

Javascript/jQuery Event Handler Scope inside object using keyword , on to set up the click and change handlers, but I was having problems with scope there as well. Any help, again, is much appreciated. (function ($)  Firstly, it is event, not event handler, which is being raised. Event handler is a method that subsribes to a given event. Secondly, scope only governs member visibility at compile time and does not affect event subscriptions. If event is visible, it works.

Better do something simple like

$('[id^="box-content-"]').click(function () {//one single event for all your languages
    var lang = this.id.split('-')[2];//get the lang from the id 
    switchLang('menu', lang);//call the function
});

Scoping variables appropriately in event handlers, A common mistake in programming event handlers is connecting the event handler to an object that has been declared with a scope too limited connect event handlers, this issue is less common in languages such as Visual  The problem Invoking event handlers in C# has always been a bit of a pain, because an event with no subscribers is usually represented as a null reference. This leads to code like this: It's important to use the handler local variable, as if instead you access the field twice, it's possible that the last…

Javascript event listener scope - JavaScript, Do event listeners run in the global scope and if so does a global scoped try If so then my problem is solved I can put the try block around that  JavaScript ‘this’ and Event Handlers. If there’s one reason to rely on a JavaScript library such as jQuery, it’s event handling. Most libraries abstract events into a uniform set of

How to Fix JavaScript Callbacks Variable Scope Problems , This is usually the case when using internal APIs that depend on an external event. For example, processing a response after an HTTP request is  public interface EventHandler This interface represents a handler for discrete events triggered during ODE integration. Some events can be triggered at discrete times as an ODE problem is solved.

Event Handler Scope (ActionScript: The Definitive Guide), We'll consider event handler scope in relation to movie clip events, button events "Method versus global function overlap issues", in Chapter 13, "Movie Clips". When a function is invoked in JavaScript, you can follow these steps to determine what this will be (these rules are in priority order): If the function was the result of a call to function#bind, this will be the argument given to bind If the function was invoked in the form foo.func(), this will be foo.

Comments
  • Change var currentLang = ... to let currentLang = .... Alternatively, avoid the loop entirely by putting the same class on all the elements and storing the language value in a data attribute. Then you can read that attribute out on click.
  • As @RoryMcCrossan mentioned, use let. var is defined in the functional scope, whereas let is defined in the block scope.
  • @Alex var is defined in the global scope, you of course meant functional scope, and let is block scope..
  • Yeah @Keith, just different wording, same idea. +
  • Why you create new variable currentLang at all?
  • I was supposed to edit my own post and accidentally pressed on yours without thinking :)
  • I approved it as is :)