Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

auto-bind2

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

auto-bind2

An ES6 class method automatic binder

  • 1.0.3
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

ES6 Class Auto Binder

A Javascript ES6 class autoBind() function with a customizable filter and defaults for React.

Why Build This?

This package exposes an autoBind function that calls bind() on 'methods' in you ES6 class so that this always refers to the class object instance and not window or some other random object. It avoids the need to call bind() multiple times in your constructor, like this:

class Foo {
  constructor() {
    this.onClick = this.onClick.bind()
    this.onDrag = this.onDrag.bind()
    this.onWhatever = this.onWhatever.bind()
    ...
  }
  ...
}

Instead you just write:

class Foo {
  constructor() {
    autoBind(this)
  }
  ...
}

There are a few autoBind functions out there already, and they work great. However what I really felt was needed was a fully customizable function that used a filter callback so that it would work with whatever naming conventions you used for your callback functions.

Usage

Install the package with:

npm install auto-bind2

Import it using:

import autoBind from 'auto-bind2'
// OR
var autoBind = require('auto-bind2')

The function takes a this pointer and an optional filter method, e.g.:

autoBind(this)

autoBind(this, (funcName) => (funcName.startsWith('on')))

autoBind(this, (funcName) => (['onClick', 'onDrag', 'onEvent'].includes(funcName)))

The library includes support for React. React Component methods are already bound, so you can exclude them with:

import { reactAutoBind } from 'auto-bind2'

reactAutoBind(this)

or:

import { isReactMethod, autoBind } from 'auto-bind2'

autoBind(this, isReactMethod)

About

The code is written in ES6 Javascript and built to target NodeJS v8, Chrome v60 and uglification.

Keywords

FAQs

Package last updated on 16 Oct 2017

Did you know?

Socket

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
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc