Conditional html mapping with knockout

I have a knockout observable array of actions that contains audits and comments. I have data from the server and sorted by an array of actions based on the timestamp of the objects.

I would like to be able to conditionally display html based on type, so the checks and comments will look different.

<!-- ko foreach: activities --> <div class="audit" data-bind="visible: {activity is typeof Audit}"> @*Do some audit html*@ </div> <div class="comment" data-bind="visible: {activity is typeof Comment}"> @*Do some comment html*@ </div> <!-- /ko --> 

I have the following html, but I donโ€™t know how this condition is, I just wrote something above as a placeholder so that you understand what I'm trying to achieve.

I probably approach this all wrong, any help is greatly appreciated!

+4
source share
2 answers

The Nayjest solution should work if you change the visible binding to an if binding - this way it will not try to display parts with a header dependency.

The best solution, however, probably consists of two patterns and their execution based on type. You may have a method on a virtual machine that takes $ data and returns, for example, "auditTemplate" or "commentTemplate" depending on the result of something like $ data instanceof Audit. Then you will have two templates built into the script tags with these identifiers:

 <script id="auditTemplate" type="text/html"> <div class="audit"> <!-- Do some audit stuff --> </div> </script> <script id="commentTemplate" type="text/html"> <div class="comment"> <!-- Do some comment stuff --> </div> </script> 

And then in your virtual machine you will have something like:

 this.getTemplate = function(data) { return (data instanceof Audit) ? 'auditTemplate' : 'commentTemplate' } 

On the html page you will do something like:

 <!-- ko foreach: activities --> <div databind="template: {name:$parent.getTemplate($data), data: $data}"></div> <!-- /ko --> 
+3
source

If you have an Audit class that is visible in the global scope and properties of the โ€œactivitiesโ€ of the view model, try something like this:

 <div data-bind="foreach: activities"> <div data-bind="visible: $data instanceof Audit"> <h1 data-bind="text: $data.title"></h1> <!-- Some other data here --> </div> </div> 
+2
source

All Articles