Skip to content

Instantly share code, notes, and snippets.

@tdreyno
Created September 23, 2012 22:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tdreyno/3773238 to your computer and use it in GitHub Desktop.
Save tdreyno/3773238 to your computer and use it in GitHub Desktop.
"Single Table Inheritance" for Ember.js
/**
* A root "Model" class for Objects which have inherited types based on
* a configurable per-object value.
*/
FS.MultiplexingModel = Em.Object.extend({
});
/**
* The great hash of klasses and types
*/
FS.MultiplexingModel.klassMap = {};
/**
* Add our methods to the root class
*/
FS.MultiplexingModel.reopenClass({
/**
* Per-class type property
*/
typeProperty: "type",
/**
* Given a Object, figure out what type of descendant class it should be.
*/
descendantInstanceForObject: function(data) {
var map = FS.MultiplexingModel.klassMap,
prop = Ember.get(this, "typeProperty");
if (data[prop] && (rootKlass = map[this.toString()]) && (klassName = rootKlass[data[prop]])) {
if ('string' === typeof klassName) {
klassName = Ember.getPath(klassName);
}
return klassName.create(data);
} else {
return Em.Object.create(data);
}
},
/**
* Register a new type string and target class for this base class.
*/
registerMap: function(type, klass) {
var map = FS.MultiplexingModel.klassMap;
var key = this.toString();
var submap = map[key];
if (!submap) {
submap = {};
map[key] = submap;
}
submap[type] = klass;
}
});
@andruby
Copy link

andruby commented Jan 16, 2014

Hey @tdreyno, do you have an example of how to use this code?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment