A Backbone.js Collection of multiple Model subclasses

后端 未结 5 1576
没有蜡笔的小新
没有蜡笔的小新 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:39

    Maybe it's bad to use eval, but this is much more ruby-style way (coffeescript):

      parse: (resp)->
        _(resp).map (attrs) ->
          eval("new App.Models.#{attrs.type}(attrs)")
    

    So you don't need to write a lot of switch/cases, just set type attribute in your JSON. It works very good with rails+citier or other multitable inheritance solution. You can add new descendants without adding them to your cases.

    And you can use such constructions in other places where you need a lot of switch/cases depending on your model class.

提交回复
热议问题