andreypopp / autobind-decorator

Decorator to automatically bind methods to class instances
MIT License
1.45k stars 66 forks source link

How to pass params? #28

Closed dineshvgp closed 8 years ago

dineshvgp commented 8 years ago

Before: <button onClick={ this.handleClick.bind(this, key) }></button> After: <button onClick={ this.handleClick(key) }></button> //Not working

anrddh commented 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>
  }
}
Spivaka commented 8 years ago

@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.

anrddh commented 8 years ago

@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.

Spivaka commented 8 years ago

@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.

anrddh commented 8 years ago

@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!

Spivaka commented 8 years ago

@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...

Nitzperetz commented 8 years ago

@andreypopp , why was this issue closed? will there be no way to use autobind decorator with parameters (without the use of .bind(...))?

andreypopp commented 8 years ago

@Nitzperetz I can't see how we can implement it without the use of .bind().

Nitzperetz commented 8 years ago

See bonus section of this article: https://daveceddia.com/avoid-bind-when-passing-props/ There you could find a partial solution for passing parameters.