Created
September 23, 2012 22:16
-
-
Save tdreyno/3773238 to your computer and use it in GitHub Desktop.
"Single Table Inheritance" for Ember.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey @tdreyno, do you have an example of how to use this code?