Socket
Socket
Sign inDemoInstall

bindme

Package Overview
Dependencies
0
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    bindme

is a helper to bind a list of methods to an object reference


Version published
Weekly downloads
17
decreased by-29.17%
Maintainers
1
Created
Weekly downloads
 

Readme

Source

bindme

is a helper to bind a list of methods to an object reference

Installation | Motivation | Usage | License

Installation

npm install bindme

Motivation

I was reading some interesting articles about a React poerformance tip: creating functions in render() is not recommended.

I was looking for a way to autobind methods but none was enough convincingly in my opinion, so I created this minimal package that is implemented in 6 lines of good old ES5 code and requires really few lines of code on the user side to be imported and invoked.

Consider also that, at the time of this writing, decorator syntax is not final yet. Furthermore, this bindme helper has no dependency at all and probably will not require updates.

Usage

API is bindme(this, 'method1', 'method2', ..., 'methodN'). For example

import bindme from 'bindme'
// Also CommonJS is available:
// const bindme = require('bindme')

class MyButton extends Component {
  constructor(props) {
    super(props)

    this.state = { clicked: false }

    bindme(this, 'handleClick')
  }

  handleClick() {
    this.setState({ clicked: true })
  }
}

Since super returns an instance, the following snippet works too

  constructor(props) {
    bindme(super(props),
      'onClick',
      'onMouseOver'
    )
  }

Implementation

Code is written in ES5 for compatibility, it is equivalent to the following ES6 code

const bindme = (self, ...funcs) => {
  funcs.forEach(func => {
    if (self[func]) {
      self[func] = self[func].bind(self)
    } else {
      console.error(`Method ${func} is not defined`)
    }
  })
}

License

MIT

Keywords

FAQs

Last updated on 18 Dec 2017

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc