-
Notifications
You must be signed in to change notification settings - Fork 10
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Implement JSTP Record Data and JSTP Record Metadata #19
Comments
Conceptual code by @tshemsedinov copied from Impress: // Assign metadata to array elements
// data - array of objects serialized into arrays with JSTP single object
// metadata - data describes PrototypeClass structure
// Returns: built PrototypeClass
//
api.jstp.assignMetadata = function(data, metadata) {
var proto = api.jstp.buildPrototype(metadata);
api.jstp.assignPrototype(data, proto);
return proto;
};
// Assign prototype to records array or single record
// data - array of objects serialized into arrays with JSTP single object
// proto - dynamically built prototype to be assigned
//
api.jstp.assignPrototype = function(data, proto) {
if (Array.isArray(data)) {
data.forEach(function(item) {
item.__proto__ = proto.prototype;
});
} else {
data.__proto__ = proto.prototype;
}
};
// Build Prototype from Metadata
//
api.jstp.buildPrototype = function(metadata) {
var protoClass = function ProtoClass() {};
var index = 0, fieldDef, buildGetter, fieldType;
for (var name in metadata) {
fieldDef = metadata[name];
fieldType = typeof(fieldDef);
if (fieldType !== 'function') fieldType = fieldDef;
buildGetter = api.jstp.accessors[fieldType];
if (buildGetter) buildGetter(protoClass, name, index++, fieldDef);
}
return protoClass;
};
api.jstp.accessors = {};
api.jstp.accessors.string = function(proto, name, index) {
Object.defineProperty(proto.prototype, name, {
get: function() {
return this[index];
},
set: function(value) {
this[index] = value;
}
});
};
api.jstp.accessors.Date = function(proto, name, index) {
Object.defineProperty(proto.prototype, name, {
get: function() {
return new Date(this[index]);
},
set: function(value) {
this[index] = value instanceof Date ? value.toISOString() : value;
}
});
};
api.jstp.accessors.function = function(proto, name, index, fieldDef) {
Object.defineProperty(proto.prototype, name, { get: fieldDef });
}; |
The solution with assigning a dynamically generated prototype to an array is elegant but I see several problems here:
To conclude, it will be better to construct an object instead of assigning a prototype. Such objects will not have subtle drawbacks when working with them and, even more importantly, will work significantly faster. FYI @tshemsedinov |
We will need custom prototypes, though. For functions. Thus the basic algorithm is:
|
No description provided.
The text was updated successfully, but these errors were encountered: