Reputation: 55
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.
Upvotes: 4
Views: 53
Reputation: 742
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.
Upvotes: 2