Skip to content

Commit 6d6de56

Browse files
committed
src,doc: add documentation for per-binding state pattern
PR-URL: #32538 Reviewed-By: James M Snell <jasnell@gmail.com>
1 parent f4c2dff commit 6d6de56

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

src/README.md

+44
Original file line numberDiff line numberDiff line change
@@ -395,6 +395,50 @@ void Initialize(Local<Object> target,
395395
NODE_MODULE_CONTEXT_AWARE_INTERNAL(cares_wrap, Initialize)
396396
```
397397
398+
<a id="per-binding-state">
399+
#### Per-binding state
400+
401+
Some internal bindings, such as the HTTP parser, maintain internal state that
402+
only affects that particular binding. In that case, one common way to store
403+
that state is through the use of `Environment::BindingScope`, which gives all
404+
new functions created within it access to an object for storing such state.
405+
That object is always a [`BaseObject`][].
406+
407+
```c++
408+
// In the HTTP parser source code file:
409+
class BindingData : public BaseObject {
410+
public:
411+
BindingData(Environment* env, Local<Object> obj) : BaseObject(env, obj) {}
412+
413+
std::vector<char> parser_buffer;
414+
bool parser_buffer_in_use = false;
415+
416+
// ...
417+
};
418+
419+
// Available for binding functions, e.g. the HTTP Parser constructor:
420+
static void New(const FunctionCallbackInfo<Value>& args) {
421+
BindingData* binding_data = Unwrap<BindingData>(args.Data());
422+
new Parser(binding_data, args.This());
423+
}
424+
425+
// ... because the initialization function told the Environment to use this
426+
// BindingData class for all functions created by it:
427+
void InitializeHttpParser(Local<Object> target,
428+
Local<Value> unused,
429+
Local<Context> context,
430+
void* priv) {
431+
Environment* env = Environment::GetCurrent(context);
432+
Environment::BindingScope<BindingData> binding_scope(env);
433+
if (!binding_scope) return;
434+
BindingData* binding_data = binding_scope.data;
435+
436+
// Created within the Environment::BindingScope
437+
Local<FunctionTemplate> t = env->NewFunctionTemplate(Parser::New);
438+
...
439+
}
440+
```
441+
398442
<a id="exception-handling"></a>
399443
### Exception handling
400444

0 commit comments

Comments
 (0)