mirror of
https://github.com/zebrajr/node.git
synced 2026-01-15 12:15:26 +00:00
src,doc: add documentation for per-binding state pattern
PR-URL: https://github.com/nodejs/node/pull/32538 Reviewed-By: James M Snell <jasnell@gmail.com>
This commit is contained in:
@@ -395,6 +395,50 @@ void Initialize(Local<Object> target,
|
||||
NODE_MODULE_CONTEXT_AWARE_INTERNAL(cares_wrap, Initialize)
|
||||
```
|
||||
|
||||
<a id="per-binding-state">
|
||||
#### Per-binding state
|
||||
|
||||
Some internal bindings, such as the HTTP parser, maintain internal state that
|
||||
only affects that particular binding. In that case, one common way to store
|
||||
that state is through the use of `Environment::BindingScope`, which gives all
|
||||
new functions created within it access to an object for storing such state.
|
||||
That object is always a [`BaseObject`][].
|
||||
|
||||
```c++
|
||||
// In the HTTP parser source code file:
|
||||
class BindingData : public BaseObject {
|
||||
public:
|
||||
BindingData(Environment* env, Local<Object> obj) : BaseObject(env, obj) {}
|
||||
|
||||
std::vector<char> parser_buffer;
|
||||
bool parser_buffer_in_use = false;
|
||||
|
||||
// ...
|
||||
};
|
||||
|
||||
// Available for binding functions, e.g. the HTTP Parser constructor:
|
||||
static void New(const FunctionCallbackInfo<Value>& args) {
|
||||
BindingData* binding_data = Unwrap<BindingData>(args.Data());
|
||||
new Parser(binding_data, args.This());
|
||||
}
|
||||
|
||||
// ... because the initialization function told the Environment to use this
|
||||
// BindingData class for all functions created by it:
|
||||
void InitializeHttpParser(Local<Object> target,
|
||||
Local<Value> unused,
|
||||
Local<Context> context,
|
||||
void* priv) {
|
||||
Environment* env = Environment::GetCurrent(context);
|
||||
Environment::BindingScope<BindingData> binding_scope(env);
|
||||
if (!binding_scope) return;
|
||||
BindingData* binding_data = binding_scope.data;
|
||||
|
||||
// Created within the Environment::BindingScope
|
||||
Local<FunctionTemplate> t = env->NewFunctionTemplate(Parser::New);
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
<a id="exception-handling"></a>
|
||||
### Exception handling
|
||||
|
||||
|
||||
Reference in New Issue
Block a user