Last active
June 24, 2019 06:15
-
-
Save hereswhatidid/8553151 to your computer and use it in GitHub Desktop.
Knockout extender to group the results of an observable array.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var ViewModel = function( data ) { | |
this.observableArrayObject = ko.observableArray( data.items ).extend( { 'grouped': 4 } ); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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