Skip to content

Instantly share code, notes, and snippets.

@hereswhatidid
Last active June 24, 2019 06:15
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save hereswhatidid/8553151 to your computer and use it in GitHub Desktop.
Save hereswhatidid/8553151 to your computer and use it in GitHub Desktop.
Knockout extender to group the results of an observable array.
var ViewModel = function( data ) {
this.observableArrayObject = ko.observableArray( data.items ).extend( { 'grouped': 4 } );
};
/**
* Extends an observable array to return grouped results
* @param {observable} target Obvervable property being extended
* @param {int} numColumns Number of items to be in each group
* @return {observable} Resulting grouped array
*/
ko.extenders.grouped = function( target, numColumns ) {
var arrValues = target(),
columns = ( numColumns || 2 );
target.groupedItems = ko.computed( function() {
var rows = [],
current = [],
i = 0,
max = arrValues.length;
rows.push(current);
for ( i; i < max; i += 1) {
current.push(arrValues[i]);
if (((i + 1) % columns) === 0) {
current = [];
rows.push(current);
}
}
return rows;
}, this);
return target;
};
<div id="sampleApp">
<div data-bind="foreach: observableArrayObject.groupedItems()">
<div data-bind="foreach: $data" class="row">
<div class="col-sm-6">
<div class="checkbox">
<label data-bind="text: label"></label>
</div>
</div>
</div>
</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment