flurpleplurple flurpleplurple - 4 months ago 36
Javascript Question

How do I rewrite this ES6 code to be Safari-compatible?

I have some Vue.js code that uses ES6 arrow functions. However, apparently Safari (and it appears Chrome on OSX in one case) doesn't like this. Here's the code:

fetchItemCount: function(){
this.$http.get('/api/fetchItemCount')
.then(response => {
this.itemCount = response.data;
})
.catch(response => {

});
},


I have several functions that use the arrow syntax. How can I rewrite them to avoid using it but still perform the same work?

I have tried using Babel to transpile the code but that seems to introduce errors (Unable to set property 'Vue' of undefined or null reference)

Answer

As others have noted using a transpiler such as babel would do the trick but since that isn't always possible here is how it would look without arrow functions.

fetchItemCount: function(){
    var that = this;
    this.$http.get('/api/fetchItemCount')
        .then(function(response) {
            that.itemCount = response.data;
        })
        .catch(function(response) {

        });
},

What the arrow function gives you is essentially a function that keeps the this scope of where it's declared, so to reproduce that we just need to assign this in the outer scope to a new variable and use that inside the function.

As LinusBorg noted in the comments, when using vue-resource you don't have to do the var that = this; part since the library will change this in the callback to the outer scope for you. This is specific to vue-resource resource though and not how it's generally done with promises so it generally won't work with other libraries.