Dynamically choosing a view at runtime with Ember + Handlebars

后端 未结 4 829
眼角桃花
眼角桃花 2021-02-04 20:10

I am using Ember, Ember Data, and Handlebars to display a timeline with a number of different types of models. My current implementation, though functioning properly, seems lik

4条回答
  •  粉色の甜心
    2021-02-04 20:28

    This is just off the top of my head: I would create a separate template/view for each model type. E.g. there would be a DesignView, OrderView, etc. Each of these would specify the template to use with templateName (all code coffeescript):

    App.DesignView = Em.View.extend
      templateName: 'design'
    
    App.OrderView = Em.View.extend
      templateName: 'order'
    

    All of the custom rendering for each type would be done inside the view/template.

    At this point we need to have some template logic to decide which view to show for each item. The easiest thing to do would be to store the viewType on the model.

    App.Design = Em.Model.extend
      viewType: App.DesignView
    
    App.Order = Em.Model.extend
      viewType: App.OrderView
    

    Then the template could look like:

    {{#collection contentBinding="App.selectedAccountController.everythingSorted"}}
      {{view content.viewType contentBinding="content"}}
    {{/collection}}
    

    This is not ideal, however, since we don't want the model to know about the view layer. Instead, we could create some factory logic to create a view for a model. Then we could create a computed property on the controller which contains an array of the models and their corresponding views:

    App.selectedAccountController = Em.ArrayController.create
      ..
      viewForModel: (model) ->
        # if model is instance of Design return DesignView, Order return OrderView etc.
      everythingSortedWithViews: ( ->
        everythingSorted.map (model) ->
          {model: model, viewType: @viewForModel(model)}
      ).property('everythingSorted')
    

    The template would then look like this:

    {{#collection contentBinding="App.selectedAccountController.everythingSortedWithView"}}
      {{view content.viewType contentBinding="content.model"}}
    {{/collection}}
    

    There are probably better ways to do this. I would love to hear someone who is closer to the core of Ember give a solution.

提交回复
热议问题