How does .bind (this) work in Javascript?

1

I'm working with Javascript, which function has the functionality .bind (this)?

It appears within a form

import React from 'react';
import { Players } from './../api/players';

    export default class AddPlayer extends React.Component {
        handleSubmit(e) {
            let playerName = e.target.playerName.value;
            e.preventDefault();

            if (playerName) {
                e.target.playerName.value = '';
                // players insert
                Players.insert({
                    name: playerName,
                    score: 0   // this.props.score (puntuacion default para insercion de user)
                });
            } // if

        }
        render() {
            return (
                <div>
                    **<form onSubmit={this.handleSubmit.bind(this)}>**
                        <input type="name" name="playerName" placeholder="Introduzca el jugador" />
                        <button>Add Player</button>
                    </form>
                </div>
            );
        }

};
    
asked by Gerardo Bautista 22.07.2017 в 02:30
source

1 answer

1

It's simply to tell you that it's from the same kind of the same context, that it belongs to those classes.

A good practice would be that you bindiaras in the constructor. something like this:

import React from 'react';
import { Players } from './../api/players';

    class AddPlayer extends React.Component {

        constructor(props) {
          super(props);

          this.handleSubmit = this.handleSubmit.bind(this);          
        }

        handleSubmit(e) {
            let playerName = e.target.playerName.value;
            e.preventDefault();

            if (playerName) {
                e.target.playerName.value = '';
                // players insert
                Players.insert({
                    name: playerName,
                    score: 0   // this.props.score (puntuacion default para insercion de user)
                });
            } // if
        }

        render() {
            return (
                <div>
                    <form onSubmit={this.handleSubmit}>
                        <input type="name" name="playerName" placeholder="Introduzca el jugador" />
                        <button>Add Player</button>
                    </form>
                </div>
            );
        }

};

export default AddPlayer;
    
answered by 02.08.2017 в 17:36