Monday, 24 June 2013

Knockout - The "style" binding

The style binding adds or removes one or more style values to the associated DOM element. This is useful, for example, to highlight some value in red if it becomes negative, or to set the width of a bar to match a numerical value that changes.
<div data-bind="style: {color: currentProfit() < 0 ? 'red': 'black'}">
   Profit Information

<script type="text/javascript">
    var viewModel = {
        currentProfit: ko.observable(150000) // Positive value, so initially black
    viewModel.currentProfit(-50); // Causes the DIV's contents to go red
This will set the element’s style.color property to red whenever the currentProfit value dips below zero, and to black whenever it goes above zero.

You should pass a JavaScript object in which the property names correspond to style names, and the values correspond to the style values you wish to apply.
You can set multiple style values at once. For example, if your view model has a property called isSevere,
<div data-bind="style: {color: currentProfit() < 0 ? 'red': 'black', fontWeight: isSevere() ? 'bold': ''}">...</div>
If your parameter references an observable value, the binding will update the styles whenever the observable value changes. If the parameter doesn’t reference an observable value, it will only set the styles once and will not update them later.
As usual, you can use arbitrary JavaScript expressions or functions as parameter values. KO will evaluate them and use the resulting values to determine the style values to apply.

Applying styles whose names aren’t legal JavaScript variable names
If you want to apply a font-weight or text-decoration style, or any other style whose name isn’t a legal JavaScript identifier (e.g., because it contains a hyphen), you must use the JavaScript name for that style. For example,
  • Don’t write { font-weight: someValue }; do write { fontWeight: someValue }
  • Don’t write { text-decoration: someValue }; do write { textDecoration: someValue }

No comments:

Post a Comment