Skip to content

Instantly share code, notes, and snippets.

@adorsk
Created August 2, 2012 19:35
Show Gist options
  • Save adorsk/3239977 to your computer and use it in GitHub Desktop.
Save adorsk/3239977 to your computer and use it in GitHub Desktop.
Backbone serializer test
require([
"jquery",
"use!backbone",
"use!underscore",
"_s",
"use!ui",
],
function($, Backbone, _, _s, ui){
// Returns the class name of the argument or undefined if
// it's not a valid JavaScript object.
var getObjectClass = function(obj) {
// Define list of classes.
var knownClasses = {
'Backbone.Model': Backbone.Model
};
// If we find object's class, return it.
for (var className in knownClasses){
if (obj instanceof knownClasses[className]){
return className;
}
}
return undefined;
};
// Initialize serializers object.
var serializers = {};
// Serialize a model.
serializers['Backbone.Model'] = function(model, registry){
// Get key for model.
var modelKey = _s.sprintf('{{Backbone.Model:%s}}', model.cid);
// If model is not in the registry...
if (! registry[modelKey]){
// Initialize serialized model object.
var serializedModel = {};
// For each model attribute + cid...
_.each(_.extend(model.toJSON(), {cid: model.cid}), function(value, attr){
// Serialize the value.
serializedModel[attr] = serialize(value, registry);
});
// Save the serialized model to the registry.
registry[modelKey] = serializedModel;
}
// Return the registered model.
return modelKey;
};
// Given an object, serialize it.
// This process will also register it (and its sub-objects)
// in the registry.
var serialize = function(obj, registry){
// Get the type of the object.
var clazz = getObjectClass(obj);
// If the type has a serializer, serialize the value.
if (serializer = serializers[clazz]){
return serializer(obj, registry);
}
// Otherwise return it as-is.
else{
return obj;
}
};
var testModel = new Backbone.Model({
a: 'a',
m1: new Backbone.Model({
id: 'm1'
})
});
var registry = {};
var serializedModel = serialize(testModel, registry);
console.log("serializedModel: ", serializedModel, "registry: ", registry);
$(document).ready(function(){
console.log("document.ready");
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment