A Backbone.js Collection of multiple Model subclasses

后端 未结 5 1573
没有蜡笔的小新
没有蜡笔的小新 2020-12-07 12:13

I have a REST Json API that returns a list \"logbooks\". There are many types of logbooks that implement different but similar behavior. The server side implementation of th

5条回答
  •  感情败类
    2020-12-07 12:56

    Yes. You can override the parse function on the collection (I'm gonna use javascript instead of coffeescript, because it's what I know, but the mapping should be easy):

    LogbookCollection = Backbone.Collection.extend({
        model: Logbook,
        url: "/api/logbooks",
        parse: function(response){
          var self = this;
          _.each(response, function(logbook){
              switch(logbook.type){
                 case "ULM":
                   self.add(new UmlLogBook(logbook);
                   break;
                 case "Plane":
                   ...
              }
          }
        }
     });
    

    Hope this helps.

提交回复
热议问题