├── .gitignore ├── .npmignore ├── LICENSE.md ├── README.md ├── package.json ├── src └── index.js └── test └── index.jsx /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | lib/ 3 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Gregory Benner 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # React Class Binder 2 | 3 | [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/) 4 | 5 | Automatically bind methods defined in a React component using the ES2015 class syntax (similar to how React.createClass works). 6 | 7 | This is a small package that uses a "trick" that allows mixin behavior in ES2015 using "subclass factories" so that you don't need to manually call the function in the `constructor()` function, and you don't need to resort to still unstandardized syntax like decorators or ES2015 class properties. You can read more about it [here](http://www.2ality.com/2016/05/six-nifty-es6-tricks.html#simple-mixins-via-subclass-factories). 8 | 9 | ## Installation 10 | 11 | To install the stable version: 12 | 13 | ```shell 14 | npm install --save react-class-binder 15 | ``` 16 | 17 | ## Usage 18 | This package uses a cool trick with ES2015 classes to make it extremely easy to use: 19 | 20 | ```js 21 | import React from 'react' 22 | import binder from 'react-class-binder' 23 | // If using require, do `var binder = require('react-class-binder').default` 24 | 25 | export default class ComponentName extends binder(React.Component) { 26 | // ...component stuff here 27 | } 28 | 29 | ``` 30 | 31 | No other configuration or options are needed! `react-class-binder` will only bind what is absolutely necessary, so it won't touch React related method, nor will it rebind any method on any class that extends your class. So any libraries which use inheritance or higher-order-components will work fine with `react-class-binder` (Including [`react-css-modules`](https://github.com/gajus/react-css-modules) and [`radium`](https://github.com/FormidableLabs/radium))! 32 | 33 | ## Full Example 34 | 35 | ```js 36 | import React from 'react' 37 | import binder from 'react-class-binder' 38 | 39 | // V That's all that's needed! 40 | export default class ReverseP extends binder(React.Component) { 41 | static propTypes = { 42 | text: React.PropTypes.string.isRequired 43 | } 44 | 45 | reverseText () { 46 | // `this` is magically bound to the correct context! 47 | return this.props.text.split('').reverse().join('') 48 | } 49 | 50 | // Since `this` is already "correctly bound" in React's functions, `react-class-binder` skips these 51 | componentDidMount () { 52 | console.log('Component Mounted!') 53 | } 54 | componentWillUnmount () { 55 | console.log('Component About to Unmount!') 56 | } 57 | 58 | render () { 59 | return

{this.reverseText()}

60 | } 61 | } 62 | 63 | ``` 64 | 65 | ## FAQ 66 | 67 | **Why?** 68 | I was using the `reverseText = () => {` trick for a while to allow my React functions to be "correctly bound", however it always rubbed me the wrong way. It was still unfinalized syntax, it was somewhat unintuitive to others that didn't know the trick, and it became annoying when I wanted to use async functions in a class once. So I made this package to avoid having to use that. 69 | 70 | **Why not just use one of the other packages for this?** 71 | One of them required decorators, which was a no-start because I'm trying to avoid non-standard syntax. A few others I saw used functions that were called in the constructor, which was a bit more boilerplate than I would have preferred to have in each component, and they didn't play well with other libraries that inherited from your class like `react-css-modules`. This is simple, small, and works in all cases I've tried so far. 72 | 73 | **Does this impact performance?** 74 | `react-class-binder` does all binding when the object is instantiated (in React, this is basically the componentWillMount lifecycle method). That is the only place that will take longer when using this package, and even that is so small that I can't reliably measure it. 75 | 76 | ## Inspiration & Thanks 77 | * Thanks to [`react-autobind`](https://github.com/cassiozen/React-autobind) and [`autobind-decorator`](https://github.com/andreypopp/autobind-decorator) for the idea, and for helping me figure out the edge cases I'd need to solve. 78 | * Thanks to Dr. Axel Rauschmayer of [②ality.com](http://www.2ality.com/) for the "mixins" idea. 79 | 80 | ## Contributing 81 | 82 | The code is written in ES6 using [Javascript Standard Style](https://github.com/feross/standard). Feel free to make PRs adding features you want, but please try to follow Standard. Also, documentation/readme PRs are more then welcome! 83 | 84 | ## License 85 | 86 | [MIT](LICENSE.md) Copyright (c) [Gregory Benner](https://github.com/Klathmon) 87 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-class-binder", 3 | "version": "1.0.1", 4 | "description": "Automatically binds React method when using plain ES6 classes", 5 | "main": "./lib", 6 | "scripts": { 7 | "test": "mocha --recursive --compilers js:babel-register ./test/*", 8 | "clean": "rimraf lib", 9 | "build": "babel src --out-dir lib", 10 | "prepublish": "npm run clean && npm run build" 11 | }, 12 | "repository": { 13 | "type": "git", 14 | "url": "git+https://github.com/Klathmon/react-class-binder.git" 15 | }, 16 | "standard": { 17 | "parser": "babel-eslint", 18 | "globals": [ 19 | "describe", 20 | "it", 21 | "before", 22 | "after", 23 | "beforeEach", 24 | "afterEach" 25 | ] 26 | }, 27 | "babel": { 28 | "presets": [ 29 | "es2015", 30 | "react", 31 | "stage-1" 32 | ] 33 | }, 34 | "author": "Gregory Benner (https://github.com/Klathmon)", 35 | "license": "MIT", 36 | "bugs": { 37 | "url": "https://github.com/Klathmon/react-class-binder/issues" 38 | }, 39 | "homepage": "https://github.com/Klathmon/react-class-binder#readme", 40 | "devDependencies": { 41 | "babel-cli": "6.10.1", 42 | "babel-eslint": "6.0.4", 43 | "babel-preset-es2015": "6.9.0", 44 | "babel-preset-react": "6.5.0", 45 | "babel-preset-stage-1": "^6.22.0", 46 | "chai": "3.5.0", 47 | "mocha": "2.5.3", 48 | "mocha-jsdom": "1.1.0", 49 | "react": "15.1.0", 50 | "react-addons-test-utils": "15.1.0", 51 | "rimraf": "2.5.2", 52 | "standard": "7.1.2" 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import { Component } from 'react' 2 | 3 | const methodsToIgnore = [ 4 | 'constructor', 5 | 'componentWillMount', 6 | 'componentDidMount', 7 | 'componentWillReceiveProps', 8 | 'shouldComponentUpdate', 9 | 'componentWillUpdate', 10 | 'componentDidUpdate', 11 | 'componentWillUnmount', 12 | 'render' 13 | ] 14 | 15 | export default function binder (Super) { 16 | return class extends Super { 17 | constructor (...args) { 18 | super(...args) 19 | let prototype = this 20 | // keep walking back the prototype chain until we find the "important" one 21 | // The "important" one is the one right before this one, which is 2 before React's `Component` 22 | while (true) { 23 | prototype = Object.getPrototypeOf(prototype) 24 | const parentPrototype = Object.getPrototypeOf(prototype) 25 | const grandparentPrototype = Object.getPrototypeOf(parentPrototype) 26 | if (parentPrototype instanceof Component && !(grandparentPrototype instanceof Component)) { 27 | // At this point the prototype we want to work with is in the variable `prototype` 28 | // So let's get it's properties, and set them all to bind on this! 29 | for (let methodName of Object.getOwnPropertyNames(prototype)) { 30 | // Don't bother binding any methods that don't need it... 31 | if (!!~methodsToIgnore.indexOf(methodName)) continue // eslint-disable-line no-extra-boolean-cast 32 | 33 | this[methodName] = prototype[methodName].bind(this) 34 | } 35 | break 36 | } 37 | } 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /test/index.jsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import jsdom from 'mocha-jsdom' 3 | import binder from '../src/index' 4 | import { expect } from 'chai' 5 | import { renderIntoDocument } from 'react-addons-test-utils' 6 | 7 | class ReverseP extends binder(React.Component) { 8 | static propTypes = { 9 | text: React.PropTypes.string.isRequired 10 | } 11 | 12 | reverseText () { 13 | // `this` is magically bound to the correct context! 14 | return this.props.text.split('').reverse().join('') 15 | } 16 | 17 | render () { 18 | return

{this.reverseText()}

19 | } 20 | } 21 | 22 | class ExtendedReverseP extends ReverseP { 23 | testThis () { 24 | return Object.getOwnPropertyNames(this) 25 | } 26 | } 27 | 28 | describe('binder mixin', () => { 29 | jsdom() 30 | 31 | it('renders without errors', () => { 32 | const component = renderIntoDocument() 33 | 34 | expect(component.reverseText()).to.equal('tset') 35 | }) 36 | it('does not break extended classes', () => { 37 | const component = renderIntoDocument() 38 | 39 | expect(component.reverseText()).to.equal('tset') 40 | 41 | const extendedThis = component.testThis() 42 | expect(extendedThis).to.not.include('testThis') 43 | }) 44 | }) 45 | --------------------------------------------------------------------------------