protector
Protects your functions from being called twice.
Installation
npm install --save protector
Usage
Protector wraps any function so it will be called only one time. Additionally, it allows you to choose when it will run: immediately (in the same tick) or in the next tick (through process.nextTick or setImmediate).
Protector(fn) / Protector.callback(fn)
- Returns a function that can only be called once an will execute immediately when invoked.Protector.nextTick(fn)
- Returns a function that can only be called once an will execute usingprocess.nextTick
when invoked.Protector.setImmediate(fn)
- Returns a function that can only be called once an will execute usingsetImmediate
when invoked.
Example (JavaScript)
Protector = ; { callback = ; // or ... // callback = Protector.callback(callback) // callback = Protector.nextTick(callback); // callback = Protector.setImmediate(callback); // this will execute ; // this won't fire! ; // neither does this ... ;} // will print a single line in the console even that internally // it calls the callback multiple times;
Example (CoffeeScript)
Protector = require "protector" = callback = Protector callback # or ... # callback = Protector.callback callback # callback = Protector.nextTick callback # callback = Protector.setImmediate callback callback "some error" callback null ok: 1 callback # will print a single line in the console even that internally # it calls the callback multiple times processor consolelog "Hey, I can only be called once!"
Pattern
Basically Protector just wraps the given function into another function. It just simplifies writing callback protection, so:
{ callback = ; ;}
is the same as writing
{ { calledback = false; return { if!calledback calledback = true; ; } } ;}
TODO
- Handle NULL callbacks.
- Scope callback "this" to an arbitrary value.