I’ve got a list of polymorphic items, each of which corresponds to a different component which needs to be displayed.
The type of the item can change at any time, at which point the component needs to change.
Initially I just had a bunch of {{#if...}}
statements like:
{{#if isBlue}} {{blue-item item=item ...}} {{/if}}
{{#if isRed}} {{red-item item=item ...}} {{/if}}
{{#if isGreen}} {{green-item item=item ...}} {{/if}}
This works, but is rather unwieldy especially as each one has a bunch of attributes & event bindings, all of which are the same for each component type. There’s currently 7 different types and this will only grow over time, with the {{if}}
's that means there’s 7 lots of metamorph tags and associated overhead. There will be quite a few items in this list so I’d like the overhead to be as little as possible.
I’ve tried to tidy this by creating a helper which renders the right component type:
Ember.Handlebars.registerBoundHelper 'component-for-type', (type, options) ->
name = switch type
when 'red' then "red-item"
when 'blue' then "blue-item"
when 'green' then "green-item"
else throw new Ember.Error("no component found for '#{type}'")
helper = Ember.Handlebars.resolveHelper(options.data.view.container, name)
helper.call(this, options)
That means I can replace all the {{if}}
's with one:
{{component-for-type item.type
item=item
selectedItem=selectedItem
onSelect="select"
onChange="change"
...
}}
This works for the initial render, but when the items type changes it blows up because the helper is trying to call view.appendChild
on an already rendered view which isn’t allowed.
Another approach I’ve thought of is to render a partial based on the item type, I think that’ll get rid of all the ifs, but leaves me with 7 almost identical templates to maintain.
Anyone any thoughts?