Knockout: Render template based on object type

Created on 20 Jul 2019  路  5Comments  路  Source: knockout/knockout

Hello,

I am implementing a questionary and I am looking for an advice regarding the implementation. There are multiple question type: some require the user to type answer, others to select radio buttons and so on.

What I'd like is to have a different javascript class for each type of question, and have knockout render each question object using a template chosen automatically based on the object type.

What I am asking for is general advice regarding the best way to implement this. Right now my idea is to use the foreach binding and withing this loop, use if bindings to check the object type.

However I wondering if there is an elegant way to solve this problem using components or something similar. I'd like to make it reusable and to encapsulate this logic as much as possible.

Thank you

Most helpful comment

All 5 comments

Okay, I think what I am after is a way to choose a template based on a parameter of the viewModel, however in the component handler, the template function does not seem to have access to the state of the viewModel function.

My understanding is that what I'd need to do is implement a custom componentLoader to register a custom loadTemplate function, so the question is: how can I add custom values to the templateConfig property of the loadTemplate function?

https://knockoutjs.com/documentation/component-binding.html

https://knockoutjs.com/documentation/component-loaders.html

I think the encapsulation of the various types of question/answer is ideal but not very useful, as there is no real complexity for each type.
A simple example: https://codepen.io/bludev/pen/aevYrN

We do something similar to what you are asking (if I am interpreting your use case correct):

We have a component-per-type arragement, such that we get the component name to use for the given type, seen here:

https://github.com/OHDSI/Atlas/blob/master/js/components/cohortbuilder/components/CohortExpressionEditor.js#L361

You register a ko component with a given name that matches the given type. You pass the data as a param value to the component, and the component is responsible for providing the UI element to modify the type.

Example of one of the components:
Template: https://github.com/OHDSI/Atlas/blob/master/js/components/cohortbuilder/components/ConditionOccurrenceTemplate.html
ViewModel: https://github.com/OHDSI/Atlas/blob/master/js/components/cohortbuilder/components/ConditionOccurrence.js

Thank you all, this was massively helpful! @avickers perfectly addressed my question but @bluedev's remark was very spot on. While I will not go with your approach on that one @chrisknoll thank you so much for sharing it, it was very inspiring.

Thank you very much

Was this page helpful?
0 / 5 - 0 ratings