Last active
December 19, 2015 12:28
-
-
Save monokrome/5954751 to your computer and use it in GitHub Desktop.
Polymorphic relatedModel for backbone-associations
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
{polymorphic} = require 'polymorphic' | |
class OtherModel extends Backbone.Model | |
class YetAnotherOtherModel extends Backbone.Model | |
class MyModel extends Backbone.Model | |
relations: [ | |
type: Backbone.One | |
key: 'otherUri' | |
relatedModel: polymorphic 'otherUri', OtherModel, YetAnotherOtherModel | |
] |
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
# Provides polymorphic relations | |
polymorphic = (key) -> | |
# Allow a list of models or multiple arguments | |
if _.isArray arguments[1] | |
models = arguments[1] | |
else | |
models = [] | |
# Arguments isn't an array / doesn't have slice, so | |
# we'll have to do this the old fashion way. | |
i = 1 | |
while i < arguments.length | |
models.push arguments[i] | |
++i | |
# Maps a specific model instance to it's related model type | |
mapper = (attributes) -> | |
for relation in @relations | |
if relation.key == key | |
break | |
identifier = attributes[relation.key] or @get relation.key | |
for model in models | |
if identifier? | |
searchIndex = identifier.indexOf model.prototype.urlRoot | |
if searchIndex == 0 | |
console.dir attributes | |
console.dir @ | |
return model | |
return mapper | |
module.exports = {polymorphic} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note that "key" would not be necessary in the polymorphic function if this were available:
dhruvaray/backbone-associations#50