Collection of polymorphic models

56 views
Skip to first unread message

Lucas Mendelowski

unread,
May 7, 2014, 7:41:22 AM5/7/14
to spi...@googlegroups.com
Hello,
That's my first post here :). I have a question about ajax module and models. Is it possible to use different classes for instantiate models?

Let's say I have 4 models:
- Task - base model
- TodoTask - subclass of Task
- DoingTask - subclass of Task
- DoneTask - subclass of Task

My backend returns all tasks with additional field called "type" which represent the type of the task. I would like to use that field to instantiate proper class - if type is set to 'todo' it should create TodoTask, if it's 'doing' it should create DoingTask etc.

I know in Backbone there is a special function "parse" in the collection. I was wondering if it's possible to achieve something similar in Spine.

If it's not possible maybe there is different way to achieve something similar?

Axel Nitzschner

unread,
May 7, 2014, 1:00:24 PM5/7/14
to spi...@googlegroups.com
Hi,
It'd be fine with me using just one model 'Task' with that 'type' - field and filter for that field in your controller(s), however similar to Backbons parse, you could overwrite @fromJSON in your main Task model like so (assuming your API returns an array of Tasks and Task.type exists):

@fromJSON: (arr) ->
  return unless arr
  if isArray(arr)
    for value in arr
      type = value.type
      new(Model[type+'Task']).save() if type

Let me know if that kind of works ;)
Cheers

Axel Nitzschner

unread,
May 7, 2014, 1:15:44 PM5/7/14
to spi...@googlegroups.com
amendment: I forgot to call fromJSON thereafter on your constructor, to generate the actual Task records
So the code now would look like that:

@fromJSON: (arr) ->
  return unless arr
  if isArray(arr)
    for value in arr
      type = value.type
      new(Model[type+'Task']).save() if type 
  @__super__.constructor.fromJSON.call @, arr
Message has been deleted

Lucas Mendelowski

unread,
May 9, 2014, 12:30:47 PM5/9/14
to spi...@googlegroups.com
Hi Axel,
Thank you for your reply.

It's not possible for me to test this code right now but I'm afraid it has 2 problems:
1. When you call save on a new model it will make request to the server to save the model
2. Parent's version of fromJSON method will create instances of Task model.

Btw. you don't need to use @__super__.constructor.fromJSON.call @, arr - from what I know it's enough just to use super.
Reply all
Reply to author
Forward
0 new messages