Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Как задать нужный контекст? (https://javascript.ru/forum/misc/69465-kak-zadat-nuzhnyjj-kontekst.html)

Luca 25.06.2017 17:01

Как задать нужный контекст?
 
Здравствуйте.

class Data {
      displayData(data){
        log(data);
      }
      getData(){
      let rqst =  new XMLHttpRequest();
      rqst.addEventListener('load', () => {
              if(rqst.status === 200) {
               this.displayData(rqst.responseText); /*Нужный контекст*/
              }
       })
      }

}
let any = new Data();
any.getData();

как задать нужный контекст, контекст класса для displayData?

ruslan_mart 26.06.2017 05:15

Luca, а конкретнее?

Luca 26.06.2017 16:36

конкретнее? сами просили )
import React, { Component } from 'react';
class Json extends Component {
    constructor(props) {
        super(props);
        this.state = {
            date: new Date(),
            name: '',
            profession: '',
            age: 0
        };
    }
    displayName(json){
        try {
            this.setState({name: json.name});
        } catch (e) {
            alert("Exception occured: " + e.message);
        }
    }
    displayProfession(json){
        try {
            this.setState({profession: json.profession});
        } catch (e) {
            alert("Exception occured: " + e.message);
        }
    }
    displayAge(json){
        try {
            this.setState({age: json.age});
        } catch (e) {
            console.log("Exception occured: " + e.message);
        }
    }
    displayData(data){
        try {
            console.log(data);
            let json = JSON.parse(data);
            this.displayName(json);
            this.displayProfession(json);
            this.displayAge(json);

        } catch (e) {
            console.log("Exception occured: " + e.message);
        }
    }
    getData() {
        let request = new XMLHttpRequest();
        let url = 'http://zf.loc';
        request.open('GET', url);
        request.addEventListener('load',
            (function() {
                if (request.status === 200) {
                    this.setState(JSON.parse(request.responseText));
                } else {
                    console.log("Server Error: " + request.status);
                }
            }).bind(this) /*Вот здесь я пытаюсь вызвать displayData или setState и даже с .bind(this), но получаю "Type error: setState is not a function" или "displayName is not a function"*/
            ,false);
        request.addEventListener('error', function () {
            console.log("Can't Make AJAX Request");
        }, false);
        request.send();
    }

    componentDidMount() {
        this.timerID = setInterval(
            this.getData,
            3000
        );
    }
    componentWillUnmount() {
        clearInterval(this.timerID);
    }

    render() {
        return (
            <div>
                <h1>Hello, {this.state.name}</h1>
                <h2>Your profession is {this.state.profession}.</h2>
                <h2> Your age {this.state.age}</h2>
            </div>
        );
    }
}
export default Json;


"Балуюсь" с React и вот не видит у меня функция другую... Может не в контексте дело?

EmperioAf 26.06.2017 18:24

componentDidMount() {
        this.timerID = setInterval(
            this.getData.bind(this),
            3000
        );
    }


Ну и еще в es-next можно так писать:

class Json extends Component {
    ...
    getData = () => {
        ...
    }
    componentDidMount() {
        this.timerID = setInterval(
            this.getData,
            3000
        );
    }
}

А еще можно использовать оператор :: в es-next



Ну и в реакте есть еще рабочая практика: функциям, которые будут вызываться в интервалах, или в хендлере события, контекст привязывают в конструкторе.

class Json extends Component {
    constructor(props) {
        super(props);
        this.getData = this.getData.bind(this);
        ...
    }
}

Luca 27.06.2017 08:11

this.doAny = this.doAny.bind(this);

любая нормальная программа должна читаться на естественном язые и в данном случае звучит так: "функция данного объекта это функция данного объекта в контексте объекта, которому она принадлжеит" :haha:
выглядит ужасно, но работает :dance:
спасибо


Часовой пояс GMT +3, время: 01:24.