Well essentially I'm trying to populate a Bootstrap template via Knockout and a JSON object.
Bootstrap scaffolding:
<div class="row-fluid">
<div class="span4">
<h1>App Title</h1>
<p>App Description</p>
</div>
<div class="span4">
<h1>App Title</h1>
<p>App Description</p>
</div>
<div class="span4">
<h1>App Title</h1>
<p>App Description</p>
</div>
</div>
<div class="row-fluid">
<div class="span4">
<h1>App Title</h1>
<p>App Description</p>
</div>
<div class="span4">
<h1>App Title</h1>
<p>App Description</p>
</div>
<div class="span4">
<h1>App Title</h1>
<p>App Description</p>
</div>
</div>
...
Here is the Knockout code we're using:
var viewModel;
$.get('AppData.json', function (data) {
jsonData = $.parseJSON(data);
viewModel = ko.mapping.fromJS(jsonData);
var apps = viewModel.Apps();
ko.applyBindings(viewModel);
});
The problem is that I cannot get Knockout to inject the </div><div class="row-fluid">
required after running a knockout conditional of index modulo 3... I'm assuming because those <div>
tags are dangling / not closed.
In short, how do I get viewModel.Apps();
's array of objects to fit within the above Bootstrap scaffolding?
Make a computed observable which slices
apps
observable/observable array into arrays of three elements, and then bind some root element to it withforeach
binding. Something like this.Observable:
Markup:
I´m using bootstrap3 and wanted to have x objects per row, where x is depending on the window size e.g on the col class.
e.g i have elements with class :
so
if xs then a row has 3 items
if lg then a row has 6 items ...
I extended the answer of rkhayrov to put it to work
i added a dependency to width and height, which are observables So the functions will be recomputed if window is resized
and the resize handler
it just works like a Charme, the rows are generated nicely for each device-width
i leave it here if anyone needs to achieve the same
I had to solve a very similar problem myself: rendering bootstrap grids with an observable array but with bootstrap v3 and ko v3.0. I'll leave my solution here for future reference.
I'm using a plain function instead of a computed one, since binding are implemented using them by default (see RP Niemeyer answer here https://stackoverflow.com/a/6712389/323751)
In my View Model:
Template:
Hope somebody find this useful.