Your best bet is to use a custom binding. You can either place your custom binding after foreach
in the list of bindings in your data-bind
or you could execute your code in a setTimeout
to allow foreach
to generate the content before your code is executed.
Here is a sample that shows running code a single time and running code each time that your observableArray updates: http://jsfiddle.net/rniemeyer/Ampng/
HTML:
<table data-bind="foreach: items, updateTableOnce: true">
<tr>
<td data-bind="text: id"></td>
<td data-bind="text: name"></td>
</tr>
</table>
<hr/>
<table data-bind="foreach: items, updateTableEachTimeItChanges: true">
<tr>
<td data-bind="text: id"></td>
<td data-bind="text: name"></td>
</tr>
</table>
<button data-bind="click: addItem">Add Item</button>
JS:
var getRandomColor = function() {
return 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
};
ko.bindingHandlers.updateTableOnce = {
init: function(element) {
$(element).css("color", getRandomColor());
}
};
//this binding currently takes advantage of the fact that all bindings in a data-bind will be triggered together, so it can use the "foreach" dependencies
ko.bindingHandlers.updateTableEachTimeItChanges = {
update: function(element) {
$(element).css("color", getRandomColor());
}
};
var viewModel = {
items: ko.observableArray([
{ id: 1, name: "one" },
{ id: 1, name: "one" },
{ id: 1, name: "one" }
]),
addItem: function() {
this.items.push({ id: 0, name: "new" });
}
};
ko.applyBindings(viewModel);