0

How do I use the variable from the outer scope of the function. I have created this simple example here

var view = {
    init(){
    const targetOne = document.querySelector(".targetOne"); 
    const targetTwo = document.querySelector(".targetTwo"); 
    var val = "outer scope";

    targetOne.addEventListener('click', (e) => {
      console.log('target one', val)

    });
    targetTwo.addEventListener('click', this.handleEvent);
  },

  handleEvent(e) {
        console.log('targetTwo ', val);
    }
}

view.init(); 

JS fiddle link: https://jsfiddle.net/jr7b521x/50/

For the targetOne callback I can use the variable val, but when i define a function for the targetTwo callback, that variable val is not defined in the scope. I feel like I am missing something very simple here, I refreshed on scope chaining and closure but I am not able to get it

Tenzin Choklang
  • 504
  • 1
  • 5
  • 21
  • `val` is in scope only in the `init` function; i'm not sure what made you believe it would be available outside it. – Dave Newton Nov 15 '19 at 19:36
  • 1
    omg, based on where it sits lexically right? thats why targetOne call back is able to log val, because that function sits lexically inside of init. Am i right? – Tenzin Choklang Nov 15 '19 at 19:38
  • This is because the callback to targetOne listner is an inline function and hence it has the same context as that of it's parent. However , the second one isn't, you'll need to exlplicitly pass that as a parameter. – Anirudh Panchangam Nov 15 '19 at 19:39
  • You need to make a closure, like you did for `targetOne` - there's no way around this if `val` is local to the `init` scope only. You can call the `handleEvent` method from that closure and pass the value as an argument if you want. Alternatively, store the value somewhere else - not (only) a local variable - so that `handleEvent` can access it. – Bergi Nov 15 '19 at 19:40
  • @Bergi I am confused as to how to pass the event along with the call back. If i do something like this.handleKeydown.bind(null, e, val). how does the handleEvent method get the event object? – Tenzin Choklang Nov 15 '19 at 19:48
  • @TenzinChoklang You cannot bind `e` as it doesn't exist yet when you create the handler. You can pass `this.handleKeydown.bind(this, val)` and have a `handleEvent(val, e) { … }` method, or you just write `(e) => this.handleKeydown(e, val)` – Bergi Nov 15 '19 at 19:55
  • gotcha thats what I was thinking, i need the function to capture the event, then i can pass it to the handleKeydown function, thanks! – Tenzin Choklang Nov 15 '19 at 19:59

1 Answers1

0

the variable val is within the scope of the init () function

for you to get it in the handleEvent function you will need to pass it by parameter or it must be a property of the view object

Henrique Viana
  • 645
  • 4
  • 12