Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying a % style binding with knockout via function not working

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>
like image 586
jokulmorder Avatar asked Sep 19 '13 18:09

jokulmorder


People also ask

How do you activate Knockout?

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.

What are the types of binding supported by Knockout JS?

Binding Values The binding value can be a single value, literal, a variable or can be a JavaScript expression.

What is binding in Knockout?

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) .

What is two way binding in Knockout JS?

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.


3 Answers

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.

like image 187
Kyle Macey Avatar answered Sep 20 '22 17:09

Kyle Macey


This is working fine:

<div data-bind="style: { width: function() + '%' }"></div>

jsFiddle: http://jsfiddle.net/LkqTU/31377/

like image 30
wojtekc Avatar answered Sep 17 '22 17:09

wojtekc


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>
like image 38
jokulmorder Avatar answered Sep 19 '22 17:09

jokulmorder