Skip to content

jBinary.Template

Ingvar Stepanyan edited this page Sep 2, 2013 · 2 revisions

Constructor

jBinary.Template is useful when you want to wrap some basic type but override some of it's options or functionality.

Creating is pretty similar to simple custom type:

  • jBinary.Template(config)

Base type

Base type for template should be specified using one of the following methods:

  • Config option baseType - static base type.
  • Property baseType set inside setParams initialization method.
  • Config property getBaseType(context) - method to get base type dynamically depending on current context in the moment of creating property before I/O operation.

First two cases are preferred if possible since they will automatically resolve and cache underlying type.

Extra methods

jBinary.Template instance has following extra methods compared to jBinary.Type that you can use in your implementations:

  • baseRead() - reads underlying type value.
  • baseWrite(data) - writes value as underlying type.

Example

var binary = new jBinary([0x00, 0x03, 0x04, 0x05, 0x06, 0x07], {
  DynamicArray: jBinary.Template({
    setParams: function (itemType) {
      this.baseType = {
        length: 'uint16',
        values: ['array', itemType, 'length']
      };
    },
    read: function () {
      return this.baseRead().values;
    },
    write: function (values) {
      this.baseWrite({
        length: values.length,
        values: values
      });
    }
  }),

  byteArray: ['DynamicArray', 'uint8']
});

var byteArray = binary.read('byteArray'); // [0x04, 0x05, 0x06]
Something went wrong with that request. Please try again.