Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout JS - CSS Binding with dash in class name

I have a data binding in Knockout to apply a CSS class if a condition is true. When I use a dash in the class name (such as test-class) then I get a javascript error.

Here is a fiddle that demonstrates the problem: http://jsfiddle.net/sgvem/2/

<p data-bind="text: property, css: { with-dash: property().length > 0 }"></p> 

Is there a way to add a class with a dash using Knockout JS?

like image 328
Dismissile Avatar asked Apr 23 '12 15:04

Dismissile


People also ask

What is binding in KnockoutJS?

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 KnockoutJS?

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.


1 Answers

Just put it in quotes:

<p data-bind="text: property, css: { 'with-dash': property().length > 0 }"></p> 

Here's an updated fiddle.

As a side note, you don't need the > 0 since a length of 0 will evaluate to false, and any other length will evaluate to true:

<p data-bind="text: property, css: { 'with-dash': property().length }"></p> 
like image 186
James Allardice Avatar answered Sep 17 '22 16:09

James Allardice