基本上我正在尝试通过Knockout和
JSON对象填充Bootstrap模板.
Bootstrap脚手架:
@H_301_4@<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> ...这是我们正在使用的Knockout代码:
@H_301_4@var viewmodel; $.get('AppData.json',function (data) { jsonData = $.parseJSON(data); viewmodel = ko.mapping.fromJS(jsonData); var apps = viewmodel.Apps(); ko.applyBindings(viewmodel); });问题是我无法让Knockout注入< / div>< div class =“row-fluid”>在以索引模3为条件运行淘汰赛后需要…我假设因为那些< div>标签悬空/未关闭.
简而言之,我如何让viewmodel.Apps();的对象数组适合上面的Bootstrap脚手架?
解决方法
创建一个计算的observable,它将apps observable / observable数组切成三个元素的数组,然后使用foreach绑定将一些根元素绑定到它.像这样的东西.
观察到:
@H_301_4@viewmodel.appRows = ko.computed(function() { var apps = this.Apps(); var result = []; for (var i = 0; i < apps.length; i += 3) { var row = []; for (var j = 0; j < 3; ++j) { if (apps[i + j]) { row.push(apps[i + j]); } } result.push(row); } return result; },viewmodel);标记:
@H_301_4@<div class="container" data-bind="foreach: appRows"> <div class="row-fluid" data-bind="foreach: $data"> <div class="span4"> <h1 data-bind="text: title"></h1> <p data-bind="text: description"></p> </div> </div> </div>