diff --git a/README.md b/README.md index c11e6c4a..e987b3ea 100644 --- a/README.md +++ b/README.md @@ -220,6 +220,24 @@ Nest a parser in this position. Parse result of the nested parser is stored in t - `type` - (Required) A `Parser` object. +If a constructor is required for a nested parser, then the constructor function should be a selector +for the corresponding constructor (none, `main` or nested Parser variable name). + +```javascript +new Parser() + .create(function(param) { + if (!param) { + return {}; + } else if (param == 'main') { + //replace mainConstructorFn with main parser constructor function + return new mainConstructorFn(); + } else if (param === 'nested1') { + //replace nestedConstructorFn with nested parser constructor function + //nested1 is the varName of the nested parser + return new nestedConstructorFn();//call; + } + }) +``` ### skip(length) Skip parsing for `length` bytes. diff --git a/lib/binary_parser.js b/lib/binary_parser.js index 978e9484..51bb0c1c 100644 --- a/lib/binary_parser.js +++ b/lib/binary_parser.js @@ -203,7 +203,7 @@ Parser.prototype.getCode = function() { var ctx = new Context(); if (this.constructorFn) { - ctx.pushCode('var vars = new constructorFn();'); + ctx.pushCode('var vars = new constructorFn("main");'); } else { ctx.pushCode('var vars = {};'); } @@ -539,7 +539,11 @@ Parser.prototype.generateChoice = function(ctx) { Parser.prototype.generateNest = function(ctx) { var nestVar = ctx.generateVariable(this.varName); - ctx.pushCode('{0} = {};', nestVar); + if(this.options.type.constructorFn) { + ctx.pushCode('{0} = new constructorFn("' + this.varName + '");', nestVar); + } else { + ctx.pushCode('{0} = {};', nestVar); + } ctx.pushPath(this.varName); this.options.type.generate(ctx); ctx.popPath();