Closed dineshvgp closed 8 years ago
I believe you are using React? If so, then this is how you're supposed to use the decorator:
class Component extends React {
...
@autobind
handleClick(key) {
// handle click
}
...
render() {
return <button onClick={this.handleClick(key)}></button>
}
}
@awesomeaniruddh - This actually calls the function with the parameter (key), every time the page is rendered and doesn't bind the button to the function. It is possible to store the parameter on the state and reload it in the autobinded method - still not very convenient.
@Spivaka I didn't realise that.
Thinking about it now, I don't think there is a situation where you'd need to pass arguments to a click handler.
@awesomeaniruddh - There are some example for it (let's say you want to pass additional data when this button is clicked - you have 3 checkbox that are binded to the same method and you wish to know which one called the method). It it true, however, that when using react it's best to store state data on the state and not directly through the rendered object.
@Spivaka That's a pretty valid concern. I did a quick Google search and this is what came up:
return (
<th value={column} onClick={()=>this.handleSort(column)} >{column}</th>
);
2nd answer: https://stackoverflow.com/questions/29810914/react-js-onclick-cant-pass-value-to-method
That should work!
@awesomeaniruddh - It will work fine, but also .bind(...). This will miss the entire point of autobinding as it will create a new method in each rendering, making the GC work harder...
@andreypopp , why was this issue closed? will there be no way to use autobind decorator with parameters (without the use of .bind(...))?
@Nitzperetz I can't see how we can implement it without the use of .bind()
.
See bonus section of this article: https://daveceddia.com/avoid-bind-when-passing-props/ There you could find a partial solution for passing parameters.
Before:
<button onClick={ this.handleClick.bind(this, key) }></button>
After:<button onClick={ this.handleClick(key) }></button>
//Not working