I want to set the width of a div equal to a percentage calculated by a javascript method. I can get knockout to apply the style binding properly using this:
<div class="bar" data-bind="style: { width: '50%'}"></div>
but when I try to use a function to generate the output, it breaks:
<div class="bar" data-bind="style: { width: function(){return '50' + '%';}}"></div>
To activate Knockout, add the following line to a <script> block: ko. applyBindings(myViewModel); You can either put the script block at the bottom of your HTML document, or you can put it at the top and wrap the contents in a DOM-ready handler such as jQuery's $ function.
Binding Values The binding value can be a single value, literal, a variable or can be a JavaScript expression.
A binding context is an object that holds data that you can reference from your bindings. While applying bindings, Knockout automatically creates and manages a hierarchy of binding contexts. The root level of the hierarchy refers to the viewModel parameter you supplied to ko. applyBindings(viewModel) .
KO is able to create a two-way binding if you use value to link a form element to an Observable property, so that the changes between them are exchanged among them. If you refer a simple property on ViewModel, KO will set the form element's initial state to property value.
It looks like it won't take an anonymous function, but if you define the function as a named, method, I got it to work.
<script>
calcWidth = function(amt) {
return amt + '%';
}
</script>
<div class="bar" data-bind="style: { width: calcWidth(50)}"></div>
Note: I only found this out by trial and error on knockout's interactive tutorial. I'm not sure if there are other factors that come into play here, but this was the best I was able to come up with.
This is working fine:
<div data-bind="style: { width: function() + '%' }"></div>
jsFiddle: http://jsfiddle.net/LkqTU/31377/
It turns out you can get it to work with an anonymous function, you just need to explicitly call that function:
<div data-bind="style: { width: function(){ return '50%'; }() }"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With