I have a html section element which has a Knockout foreach binding to a collection of items on my viewmodel. This works fine rendering each item of the collection onto a div vertically down the page. I now want the items to group themselves in rows based on window size, so items appear in say, rows of 4 on a desktop browser but only 1 per row on mobile.
I did actually achieve this by creating the groups in the viewmodel and having my view element bind with a foreach to this groups property. The problem with this approach is that my viewmodel now has what I would consider a bunch of view logic in it and references the window object directly. Which is not right I don't think.
I already have a separate js file which has view specific logic in it, namely custom Knockout bindings for things like 'slideVisible'. How can I move the grouping logic out of my viewmodel and into this file? I'm guessing I won't be able to use Knockout's foreach binding if the grouping isn't done in the viewmodel?
If you need to do this dynamically in KO, then here is an example of a binding that wraps the normal
foreach
binding and creates a computed on the fly that returns a structure with rows/columns based on a "count" observable.You would use it like:
Here is a sample: http://jsfiddle.net/rniemeyer/F48XU/
For your specific case though, I would probably:
count
option and just pass in the itemscount
observable in theinit
function.resize
event handler that runs your logic and updates thecount
observable appropriately.It might look like (fill in your specific resize logic):