Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including memobind with all npm packages installed. Try it out:

var memobind = require("memobind")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

memobind v0.5.0

A simple javascript utility for function binding memoization.

Memobind

Version Build Status MIT licensed

A simple javascript utility for function binding memoization. It's motivated by the requirement of dynamic binding in React component rendering.

Install with npm

npm install memobind

Use with node.js, browserify or webpack:

var memobind = require('memobind');
memobind(context, methodName, ...args);

Motivation

A bind call or arrow function in a JSX prop will create a brand new function on every single render. This is bad for performance, as it will result in the garbage collector being invoked way more than is necessary.

A common use case of bind in render is when rendering a list, to have a separate callback per list item:

<ul>
  {this.props.items.map(item =>
    <li key={item.id} onClick={this.onItemClick.bind(this, item.id)}>
      ...
    </li>
  )}
</ul>

This is not good because it creates new functions in every update. The eslint rule jsx-no-bind is used to detect such quality issues.

To resolve the problem, memobind caches the function bind result so that it could be reused if the arguments are not changed. See below example:

<ul>
  {this.props.items.map(item =>
    <li key={item.id} onClick={memobind(this, 'onItemClick', item.id)}>
      ...
    </li>
  )}
</ul>

How it works

memobind caches the function bind result in the context object, with methodName as the key for cache object, and this[methodName] is the function to bind. So the context object should not be null, it's usually the component itself. The function binding result is stored with the key generated from arguments using JSON.stringify. In the above example, it is JSON.stringify([item.id]).

If you need to call a method on the component props or other objects, wrap it as a component method. For example:

class List extends React.Component {
  onItemClick(itemId) {
    this.props.onItemClick(itemId);
  }

  render() {
    ...
  }
}

memobind is created only for the need of bind with arguments. If there is no arguments, although memobind could be used, autobind decorator is a better choice with ES-future transpilers support such as Babel.

Examples

Simple setState call

<button onClick={memobind(this, 'setState', { popupVisible: true })}>Show Dialog</button>

License

MIT. Copyright (c) 2016 Nate Wang.

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free