M
M
Masterstvo2017-10-02 16:09:05
JavaScript
Masterstvo, 2017-10-02 16:09:05

How to return the context in this case?

Good afternoon! I can not understand in any way how it is possible to return the context in this case. Sample code below!

class App extends Component {

    constructor(props) {
        super(props);
        this.context = new (window.AudioContext || window.webkitAudioContext)();
    }

    play = () => {
        this.source = context.createBufferSource();
        this.source.buffer = this.buffer;
        this.destination = context.destination;
        this.source.connect(this.destination);
        this.source.start(0);
    };

    stop = () => {
        this.source.stop(0);
    };


    loadSoundFile = (url) => {
         let xhr = new XMLHttpRequest();
         xhr.open('GET', url, true);
         xhr.responseType = 'arraybuffer'; // важно
         xhr.onload = function(e) {
            this.context.decodeAudioData(this.response,
                function(decodedArrayBuffer) {
                    this.buffer = decodedArrayBuffer;
                }, function(e) {
                    console.log('Error decoding file', e);
                });
        };
        xhr.send();
    };

    componentDidMount() {
        this.loadSoundFile('audio/i_see_you.mp3');
    }

    render() {
        return (
            <div>
                <audio controls>
                    <source src='audio/i_see_you.mp3' />
                </audio>
            </div>
        );
    }
}

In the loadSoundFile function, when we make an AJAX request, I need to use this (specifically this.context and this.buffer). But the context in this piece of code is lost. I have not quite figured out the return of the context yet, so I ask for help from knowledgeable people !!! If possible with a little explanation)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oleg Drapeza, 2017-10-02
@Masterstvo

Option 1 - use arrow functions:

method(function() {
...
});

// заменить на 
method(() => {
...
})

Option 2 - bind the context to a variable:
const that = this;
that.context;

Read this

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question