1

I've seen lots of similar questions, but feel like I'm still missing something. I have the following code:

_setHotKeys: function(values, buttons){
    var hotKeyMap = {
            target: document, 
            binding:[]
        }; 

        values.forEach(function(value, index){
            if(value.hotkey){
                this.button = buttons[index]; 
                hotKeyMap.binding.push({
                    key: value.hotkey,
                    fn: function(key, event){
                        this._handleFillInValueButtonToggle(this.button, true); 
                    },
                    scope: this 

                }); 
            }

        }, this)    


        var keyMap = new Ext.util.KeyMap(hotKeyMap); 
},

In this function I am trying to set up hotkeys using Ext.js. This code will set up a hotkey for each of the values in the value array, but they all set this.button to the last button in the buttons array. My conclusion is that it is pushing a reference to this.button rather than the value into the array, so as the loop progresses, this value changes. How can I set it to push the value instead of the reference?

5
  • How about this._handleFillInValueButtonToggle(buttons[index], true)? Commented Jul 22, 2016 at 17:54
  • stackoverflow.com/questions/750486/… Commented Jul 22, 2016 at 17:55
  • @elclanrs that worked! for some reason I thought buttons would have been out of scope Commented Jul 22, 2016 at 17:57
  • @tibsar They are in the same scope, as the function referenced by fn and the buttons array are both inside the scope of your _setHotKeys function. Commented Jul 22, 2016 at 17:58
  • @elclanrs ah, that makes sense. If you post an answer, I'll mark it accepted Commented Jul 22, 2016 at 17:59

1 Answer 1

4

You are on the right track with that conclusion.

For every iteration of the loop, you've assigned this.button to be equal to the button at that index of the loop. If we break this out, it looks like;

this.button = buttons[0]
this.button = buttons[1]
this.button = buttons[2]

And so on until it reaches the end of the loop. Once it reaches the end of the loop this.button is equal to the last button in your array. So naturally when the hotkey event executes, it uses the reference to this.button, which points to the last button in your array.

Instead of assigning the reference to the class property, you should pass the button[index] reference to your handler directly.

...
fn: function(key, event) {
   this._handleFillInValueButtonToggle(button[index], true);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.