idempotent-bind
v1.1.0
Published
idempotent `bind` function library.
Downloads
3
Readme
idempotent-bind
idempotent bind
function library.
Abstract
A bind
function is idempotent if, whenever it is applied twice to any value, it gives the same result as if it were applied once:
bind(bind(x, this), this) === bind(x, this)
ECMAScript' Function.prototype.bind (thisArg [, arg1 [, arg2, …]])
is not idempotent.
x.bind(this).bind(this) !== x.bind(this)
Installation
npm install idempotent-bind
Usage
bind(target, thisArg)
The bind method takes two arguments, target
, thisArg
, and returns a bound function.
target
: the target functionthisArg
: The value to be passed as the this parameter to the target function when the bound function is called.
import { bind, unbind } from "idempotent-bind"
import {EventEmitter} from "events"
const emitter = new EventEmitter();
class Component {
componentWillMount(){
emitter.on("change", bind(this.onChange, this));
}
onChange(){
// do something
}
componentWillUnmount(){
// `unbind` release `bind` from Reference Cache Map and return the bound function.
emitter.removeListener("change", unbind(this.onChange, this));
// == emitter.removeListener("change", bind(this.onChange, this));
// but not release the Reference Cache Map.
}
}
bind
is not support [, arg1 [, arg2, …]
like Function.prototype.bind (thisArg [, arg1 [, arg2, …]])
.
unbind(target, thisArg)
The unbind
method takes two arguments, target
, thisArg
, and returns a bound function.
This unbind
behavior is similar to removeChild
.
var oldChild = element.removeChild(child)
two arguments is the same as bind
function.
target
: the target functionthisArg
: The value to be passed as the this parameter to the target function when the bound function is called.
import { bind, unbind } from "idempotent-bind"
import assert from "assert"
var f = function () {};
var g = bind(f, this);
assert(g === bind(f, this));
// unbind!!
unbind(f, this);
assert(g !== bind(f, this));
Tests
npm test
Contributing
- Fork it!
- Create your feature branch:
git checkout -b my-new-feature
- Commit your changes:
git commit -am 'Add some feature'
- Push to the branch:
git push origin my-new-feature
- Submit a pull request :D
License
MIT