Vue.JS + webpack build issue with event emitting

Using the eventBus template in Vue.js allows the central location to emit events so that the listening listeners can handle such events.

The following code snippets configure listeners on child components to receive an updated object serverwhen a specific user interface change occurs.

Today, I came across something when this DID'T works in a child component:

created: function() {
        eventBus.$on('serverSelected', function(server) {
            console.log('serverDetails, server=' + server.toString());
            this.server = server;
    });
},

but this DID works:

created: function() {
        eventBus.$on('serverSelected', (server) => {
            console.log('serverDetails, server=' + server.toString());
            this.server = server;
    });
},

I believe the only difference is the ES6 syntax for the callback. But should vanilla JS still work correctly?

I am very new to JS. Why is there another, and why only the second version works?

+4
1

function(){} () => {} , this .

arrow (() => {}), this ; , .

MDN, ,

,

, this, . , , eventBus.

MDN

, ( , undefined , , " " ..).

, , this Vue, server, eventBus.

, . , .

, this . - bind.

created: function() {
        eventBus.$on('serverSelected', function(server) {
            console.log('serverDetails, server=' + server.toString());
            this.server = server;
    }.bind(this));
},

.

created: function() {
        const self = this
        eventBus.$on('serverSelected', function(server) {
            console.log('serverDetails, server=' + server.toString());
            self.server = server;
    });
},

. this ?

+3

Source: https://habr.com/ru/post/1675424/


All Articles