Hacker News new | ask | show | jobs
by nip 3313 days ago
By using the property initializer syntax [1] [2]

[1] https://facebook.github.io/react/docs/handling-events.html

[2] https://babeljs.io/docs/plugins/transform-class-properties/

1 comments

That solves the problem of binding 'this', but doesn't solve the problem of supplying the index to the callback function. Essentially you have only two options for doing that.

One is to bind the callback function to a certain index in advance and then supply that callback to your child via props so it already knows the relevant index and doesn't need calling with any extra parameters. The trouble with this one is that it creates a new function every time, which is inefficient in itself and horrible if it winds up causing your child to rerender because props changed even though in practice you're passing an identical function every time.

The other is to supply a callback where the child component is responsible for supplying the extra index information when it calls the function, either by directly passing the index as a parameter or via an indirect route such as using data-* attributes as 'kentor mentioned. This is more efficient, but it creates tighter coupling between the child and parent components.

In practice, it seems most projects adopt the second strategy because the tighter coupling is usually much less of a problem in practice than the performance penalty, but neither solution is ideal. Unfortunately, JavaScript's semantics don't make it easy to have the equivalent of a "deep equal" comparison on functions that would return true for two copies of the same function with the same bound values.

Another is to wrap the first option in _.memoize so you only create functions once per argument and you don't get unnecessary rerenders. Just remember that _.memoize only uses the first arg for cache lookups.