Skip to content

Instantly share code, notes, and snippets.

@monokrome
Last active December 19, 2015 12:28
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 monokrome/5954751 to your computer and use it in GitHub Desktop.
Save monokrome/5954751 to your computer and use it in GitHub Desktop.
Polymorphic relatedModel for backbone-associations
{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
]
# 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}
@monokrome
Copy link
Author

Note that "key" would not be necessary in the polymorphic function if this were available:

dhruvaray/backbone-associations#50

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