I have an observable array with items bound to an ul. I need to calculate the width of the entire set of li items once the items have been added so I can set the width of the ul element to the total width of the child li elements.
How can I go about doing this with a foreach binding?
<div>
<h2 data-bind="visible: items().length">Test</h2>
<ul data-bind="foreach: { data: items, afterAdd: $root.myAfterAdd }">
<li data-bind="text: name"></li>
</ul>
</div>
And the JavaScript:
var viewModel = {
items: ko.observableArray([
{ name: "one" },
{ name: "two" },
{ name: "three" }
]),
myAfterAdd: function(element) {
if (element.nodeType === 1) {
alert("myAfterAdd");
}
},
addItem: function() {
this.items.push({ name: 'new' });
}
};
ko.applyBindings(viewModel);
// once foreach has finished rendering I have to set the width
// of the ul to be the total width of the children!
I tried using afterAdd so I can 'update' the width of the ul after each element is added, unfortunately I have discovered that afterAdd does not fire for the initial items! It will only fire when pushing additional items...
Note that the content inside the li items will be of unknown width :)
See this fiddle for a sample scenario.
afterRenderdoes what you want, and runs after the initial render. - KyeoticafterRenderis that it is called before the dom element is completely initialized (e.g. li item), this is giving me incorrect widths. - Umair