Skip to content

Instantly share code, notes, and snippets.

@sagiavinash
Last active April 2, 2016 12:32
Show Gist options
  • Save sagiavinash/1f644d03806f9da4390ffe5a069795db to your computer and use it in GitHub Desktop.
Save sagiavinash/1f644d03806f9da4390ffe5a069795db to your computer and use it in GitHub Desktop.
Binding namespaced methods.
/* 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