Skip to content

Instantly share code, notes, and snippets.

@topicus
Last active March 20, 2017 20:43
Show Gist options
  • Save topicus/b582dc07e5c5b625c16b6c6f2507ef38 to your computer and use it in GitHub Desktop.
Save topicus/b582dc07e5c5b625c16b6c6f2507ef38 to your computer and use it in GitHub Desktop.
How bind works
// This code doesn't make any sense.
// Just for pedagogical purposes.
class HelloComponent {
constructor(id) {
this.button = document.getElementById(id);
this.bindLog = this.log.bind(this);
// Use the bind version of log. It ties log to the object we are creating.
document.addEventListener('click', this.bindLog);
// Log function gets automatically bound to the DOM node that's being clicked
// There is no setState method at that HTMLElement so an error is thrown.
document.addEventListener('click', this.log);
}
setState(newState) {
console.log(this);
}
log() {
console.log('clicked');
this.setState({newState: 1});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment