Non-repeated element inside KnockoutJS foreach loop

59
December 11, 2019, at 08:20 AM

I am trying to create a knockout.js component (with CSS3 grids) that displays a bunch of sub-components, which I know can be done via something like:

<div class="items grid" data-bind="foreach: { data: items, as: 'item' }">
    <item-component params="data: item" class="grid-item"></item-component>
</div>

The problem is that I cannot figure out how to put a non-repeated item into this list. Ultimately, I want to generate something along these lines:

<div class="items grid">
    <div class="something-else grid-item"></div>
    <item-component class="grid-item"></item-component>
    <item-component class="grid-item"></item-component>
    <item-component class="grid-item"></item-component>
</div>

The reason I can't just put the something-else outside of the foreach-bound element is that it's also a grid item, so it has to be a direct child of the grid. It crossed my mind to manually append it via jquery's append, but with MVVM, that's a terrible idea (it doesn't work anyway).

Does anyone know a way to do this with knockout.js?

Answer 1

If I have understood your requirement correctly, it looks you need containerless control flow. It has been talked about in the 2nd point of this answer.

It allows you to do things like this:

<ul>
    <li class="header">Header item</li>
    <!-- ko foreach: myItems -->
        <li>Item <span data-bind="text: $data"></span></li>
    <!-- /ko -->
    <li class="tail">Tail item</li>
</ul>

Output:

<ul>
    <li class="header">Header item</li>
    <li>Item <span>Spoon</span></li>
    <li>Item <span>Fork</span></li>
    <li class="tail">Tail item</li>
</ul>
READ ALSO
List most recent videos from Youtube channels, code works but Youtube Data API daily quota fills up WAY too fast?

List most recent videos from Youtube channels, code works but Youtube Data API daily quota fills up WAY too fast?

My code below works, but why does it fill up the Youtube Data API's daily quota (10k queries) really fast?

47
Bind IEnumerable property of class to kendo mvc grid column

Bind IEnumerable property of class to kendo mvc grid column

Let's imagine that we have a sample class looking like this:

41
How to display related card products via slick slider in woocommerce?

How to display related card products via slick slider in woocommerce?

How to display related card products via slick slider in woocommerce? It seems to have written everything correctly, but the slider is still crookedly displayed and for some reason 1 slide eachI assume that perhaps the reason lies in the incorrect placement...

61
How to execute for all possible combinations?

How to execute for all possible combinations?

I've got this code below that generates a random 5-character codeFor example AU330, UEEHB, 2EH8D HJ1LM

50