-
Notifications
You must be signed in to change notification settings - Fork 57
jBinary.Type
Ingvar Stepanyan edited this page Apr 10, 2014
·
4 revisions
When you need extra functionality that you can't achieve using declarative syntax, you are able to create and reuse your own types in the same way standard types are used.
Creating type is simple:
jBinary.Type(config)
In property instances, you can access this.binary
for accessing jBinary
instance this property belongs to.
Config must contain following methods for I/O operations
-
read(context)
- required for reading data, gets currentcontext
in argument for internal purposes. -
write(data, context)
- required for writing data, also gets currentcontext
.
Config may contain following optional parameters:
-
params
- array of names of internal parameters to be retrieved from arguments list type was called with. -
setParams(...params...)
- additional/custom initialization method with input arguments while creating type. -
typeParams
- array of param names which should be resolved and cached as types. -
resolve(getType)
- if not set in previous parameter, inside this function type should resolve it's inner dependency types using givengetType
method so it could be cached by engine. - ...add anything else you want to be able to access in property instances...
All following methods (except toValue
) you wouldn't need to call nor override in most cases since it may break basic type functionality, so before using them make sure you really need that and are doing that right.
-
toValue(value, allowResolve = true)
- call this method on your type instance when you want to use reference arguments like they are used in standard types. -
inherit(args, getType)
- this method is internally called on creating type with given arguments (or without them) and getType provider for resolving dependencies; in most cases you shouldn't override or call it on yourself. -
createProperty(binary)
- creates property of the current type, linked to givenjBinary
instance; you may override it when you need to hook property creation, but don't forget to call an underlying method.
var binary = new jBinary([0x00, 0x03, 0x04, 0x05, 0x06, 0x07], {
DynamicArray: jBinary.Type({
params: ['itemType'],
resolve: function (getType) {
this.itemType = getType(this.itemType);
},
read: function () {
var length = this.binary.read('uint16');
return this.binary.read(['array', this.itemType, length]);
},
write: function (values) {
this.binary.write('uint16', values.length);
this.binary.write(['array', this.itemType], values);
}
}),
byteArray: ['DynamicArray', 'uint8']
});
var byteArray = binary.read('byteArray'); // [0x04, 0x05, 0x06]
For such types that are actually just functional wrappers around other types, you might want to have look at jBinary.Template.