You're probably better off using one of the existing table bindingHandlers out there. Either Knockout Contrib's KO Grid, @MichaelBest's suggested table above or any other which is already out there.
Regarding your question; binding an array is just as simple as you thought it would be, just enter the array in the binding (or bind to a property which holds an array). However, you're really asking about using a bindingHandler
to read settings from multiple bindings. To do that, use the third parameter of the init
/update
function of your bindingHandler
, the allBindings
parameter.
A simple example of such a binding could be:
ko.bindingHandlers['table'] = {
init: function(element, valueAccessor, allBindings){
var data = ko.unwrap(valueAccessor());
var columns = allBindings.get('columns');
var table = document.createElement('table');
for(var i = 0; i < data.length; i++){
var currentItem = data[i];
var row = document.createElement('tr');
for(var j = 0; j < columns.length; j++){
var column = document.createElement('td');
column.innerText = currentItem[columns[j]];
row.appendChild(column);
}
table.appendChild(row);
}
element.appendChild(table);
}
};
You would then use that bindingHandler
like:
<div data-bind="table:data, columns: ['id','firstName']"></div>
I have a working sample using the above binding at http://jsfiddle.net/TK9y2/
Do be aware that the allBindings
parameter also provides a has
method, which you should use to check if there is a binding with the name you are looking for. You can read up regarding this in the Knockout documentation on custom bindings.