Bomber
Bomber

Reputation: 10947

Do I have to use bind(this) in this method?

I am trying to open a modal and populate it with state data.

For my understanding, is it possible to structure this method other than using bind(this)? Would callbacks be an option here?

showExclusionDialog: function(){

    if(!this.state.exclusionReasons) {
        if(!this.state.exclusionReasons) {
            ExclusionLookupService.getReasons(function(reasons){
                this.setState({exclusionReasons: reasons});
            }.bind(this));
        }
    }

    if(!this.state.exclusionTypes) {
        ExclusionLookupService.getTypes(function(types){
            this.setState({exclusionTypes: types});
        }.bind(this));
    }

    if(!this.state.exclusionSessions) {
        ExclusionLookupService.getSessions(function(sessions){
            this.setState({exclusionSessions: sessions});
        }.bind(this));
    }

    this.setState({exclusionDialogShow: true});

},

Upvotes: 0

Views: 63

Answers (1)

Dan Prince
Dan Prince

Reputation: 29989

When it comes to component context, you have a few options.

Bind This

Force the context of your functions to be the component using .bind(this) on any callbacks.

ExclusionLookupService.getReasons(function(reasons){
  this.setState({exclusionReasons: reasons});
}.bind(this));

Use Component Methods

Rather than using inline function expressions, move your callbacks out to being methods on your component instead. The context for these methods is automatically bound at runtime.

showExclusionDialog: function() {
  ExclusionLookupService.getReasons(this.handleReasons);
},
handleReasons: function(reasons) {
  this.setState({exclusionReasons: reasons});
}

Alias This

Make another reference to this in the parent scope, then use it in the children.

var component = this;

ExclusionLookupService.getReasons(function(reasons){
  component.setState({exclusionReasons: reasons});
});

Use ES2015 Arrow Functions

Convert your function expressions to arrow functions, which use the context of this from the enclosing scope.

ExclusionLookupService.getReasons(reasons => {
  this.setState({exclusionReasons: reasons});
});

Note: Most ES5 transpilers will turn this into the Alias this syntax.

Use ES2016 Bind Syntax

There's an ES2016 proposal for a :: operator which bounds the LHS as the context of this to a function on the RHS.

ExclusionLookupService.getReasons(this::function(reasons){
  component.setState({exclusionReasons: reasons});
});

Note: Most ES5 transpilers will turn this into .bind(this).

Upvotes: 6

Related Questions