Last active
April 2, 2016 12:32
-
-
Save sagiavinash/1f644d03806f9da4390ffe5a069795db to your computer and use it in GitHub Desktop.
Binding namespaced methods.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* general way of writing a this bound method */ | |
class SampleComponent extends React.Component { | |
method = () => { | |
let props = this.props; // props can be accessed | |
} | |
} | |
| |
/* binding namespaced methods */ | |
| |
// Doesnt Work | |
class SampleComponent extends React.Component { | |
nameSpace = { | |
method = () => { | |
let props = this.props; // this.props is undefined | |
} | |
} | |
} | |
| |
// Works - whitebox way(preferred): | |
class SampleComponent extends React.Component { | |
nameSpace = (() => ({ | |
method: () => { | |
let props = this.props; // props can be accessed and its is visible by the arrow function that this is bound. | |
} | |
}))() | |
} | |
// Works - blackbox way: | |
class SampleComponent extends React.Component { | |
nameSpace = { | |
method() { | |
let props = this.props; | |
} | |
}; | |
componentWillMount() { | |
this.nameSpace.method.bind(this); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment