4

I'm having an issue with passing parameters to closures within my view components. If I do the below I get an error telling me this.updateSelection() is not a valid function.

methods: {
    getSelectedItems() {
        axios.get('api/model/' + this.model.id)
            .then(function(response) => {
                this.updateSelection(response.data.selectedItems);
            })
            .catch(error => {
                console.log(error);
            });
    },
    updateSelection(selectedItems) {
        this.selectedItems = selectedItems;
    },
}

I can make it work using the ECMA 6 syntax:

.then(response => {
    this.updateSelection(response.data.selectedItems);
})

But I can't work out how I would make the function available to the closure without the ECMA 6 syntax. Something like:

.then(function(response) => {
    parent.updateSelection(response.data.selectedItems);
})

Can anyone shed any light on this for me?

Thanks.

1 Answer 1

2

They key to this issue is understanding the difference between arrow functions and "normal" functions.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

I would suggest you don't use ES5 functions when you want to access this context. During the build process the transpiler (i.e. babel) will handle translating arrow functions into ES5.

Historically there were several ways of bypassing the problem. One of them was declaring a variable in the closure that would hold the value of the parent's this:

var that = this;
document.addEventListener('click', function() {
  console.log(this); // document
  console.log(that); // "this" from the parent scope
});

Another way is to use bind method:

document.addEventListener('click', (function() {
  console.log(this); // "this" from the parent scope
}).bind(this));

Which was commonly used i.e. in React until only recently, but people started to switch to arrow functions anyway, so the need decreased significantly.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Uriziel. This is a great answer, well structured and really helps to clarify the issue for me. Much appreciated :)

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.