craigwebster's avatar

React & Pusher

Getting confused with "this" again!

I got this working using the myThis hack but can't understand why using .bind(this) on the channel doesn't work...can any js guru explain?

    // Register pusher listener
    componentDidMount:  function() {
        var pusher = new Pusher('18262.........c037');   
        var channel = pusher.subscribe('test_channel');
        var myThis = this;

        channel.bind('my_event', function(data) {
            myThis.setState({ message : data.message });
        });
    },
0 likes
2 replies
MartelliEnrico's avatar
Level 3

I'm no Javascript guru, but I think you can do something like this:

channel.bind('my_event', function(data) {
    this.setState({ message: data.message });
}.bind(this));
craigwebster's avatar

Yes thanks @MartelliEnrico I was close but no cigar !

channel.bind('my_event', function(data) {
    this.setState({ message: data.message });
}).bind(this);

:-o

Please or to participate in this conversation.