KO custom binding for consistent column width
by bombo
HTML
<script src="https://github.com/downloads/SteveSanderson/knockout/knockout-1.2.1.debug.js"></script>
<div id="header">
<div data-bind="autoWidth: other">
krz. Übsch.
</div>
<div data-bind="autoWidth: myWidth">
Lange Überschrift
</div>
</div>
<div id="body">
<div data-bind="autoWidth: other">
Long Content
</div>
<div data-bind="autoWidth: myWidth">
Content
</div>
</div>
CSS
div div {
padding: 2px;
}
#header div {
float: left;
border: 1px solid black;
}
#body {
clear: both;
}
#body div {
float: left;
bordeR: 1px solid black;
}
JavaScript
var viewModel = {
myWidth: ko.observable(),
other: ko.observable()
};
ko.bindingHandlers.autoWidth = {
init: function(element, valueAccessor) {
var value = valueAccessor();
if (!value()) {
value(0);
}
},
update: function(element, valueAccessor, allBindingsAccessor, viewModel) {
var value = valueAccessor(),
$element = $(element);
if ($element.width() > value()) {
value($element.width());
} else {
$element.width(value());
}
}
};
$(document).ready(function() {
ko.applyBindings(viewModel);
});