access this in callback ecma6

1

Friends, I have the following code:

Selection Object (in the method to obtain is the relevant code):

class Seleccion extends React.Component{

constructor(){
    super();
    this.state ={
        image : null,
        selecciones:[]
    }
    this.obtener();
}

obtener(){
    var seleccion = this;
    API.consulta({
        metodo: 'listas/selecciones',
        'callback': function (r) {
            console.log("can we proccess?",r);
            let selecciones = [];
            selecciones.push = r.selecciones;
            seleccion.setState({
                selecciones:r.selecciones
            })
            console.log("cambiado 2",seleccion.state);


        }
    });
}
//más codigo de la clase seleccion

}

API.js

 consulta: function (data) {
        console.log("llamada desde API");
        let parametros = this.default;
        console.log("binding this?",data);
        let url = this.obtUrl(data.metodo);

        if (!data.hasOwnProperty('metodo'))  throw Error('No se ha pasado el metodo a consultar');
        if (!data.hasOwnProperty('callback'))  throw Error('No se ha pasado la funcion callback');

        parametros = Object.assign({},this.default,{
            dataType: 'jsonp',
            url: url
        })

        console.log("url",parametros.url);
        if (data.hasOwnProperty('parametros')) parametros = $.extend(this.default, data.parametros);

        if (data.hasOwnProperty('data'))
            parametros.data = data.data;

        $.ajax(parametros)
            .done(data.callback)
            .fail(function(){
                console.log("something wrong");
            })
        ;
    },

At this time, I need to access the "select" object in the callback function to make changes to the state, depending on the response. But if I pass a ".bind (this)" to the query method, it exploits me. How can I do?.

The issue is that with the ajax query I obtain the data of "selections" and depending on the result, I will have to modify the state of the same to render them, that is why I need from the callback function to access to the Selection object. PD : I know that overwriting the variable or renaming it could be accessed, but I understand that with ecma6 there is a new way. Is it like that? thanks.

    
asked by jrodriguez 22.01.2017 в 16:54
source

1 answer

0

If you want to change the context of this in your callback with ES5, it would be enough to create a copy of it with the help of bind in the following way (for example):

.done(data.callback.bind(data)) 

Passing as parameter to bind the value of this that you want to use.

In case of ES6 you could solve it with the implementation of arrow functions () => { } . Look at methodA of class A of the following example:

var API = {
  query: data => {
    // Algo asincrono como un ajax iria aqui...
    // Simulemos con setTimeout:
    setTimeout(data.callback, 1000);
  }
};

class A {
  constructor() { this.state = false }
  
  methodA() {
    API.query({
      callback: () => {
        this.state = true;
        console.log(Object.keys(this));
      }
    });
  }
  
  methodB() {
    API.query({
      callback: function() {
        console.log(Object.keys(this));
      }
    });
  }
}

const a = new A();
a.methodA(); // Propiedades de la clase A (objeto 'a')
a.methodB(); // Objeto window
    
answered by 22.01.2017 / 19:08
source