Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout JS - Use both static class name as well as data bound class name

Tags:

knockout.js

Anyone know if I can have an html element with both a static class name as well as a dynamic, data-bound class name using KnockoutJS? Something like this:

<span class='staticClassName {{viewModelPropertyValue}}'></span>

I realize this isn't ko syntax, I'm just using this syntax to get the point across.

like image 953
Bob Lauer Avatar asked Mar 13 '12 03:03

Bob Lauer


People also ask

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.

What is data bind in knockout JS?

The "data-bind" attribute contains a collection of comma-separated options for how Knockout should bind a view model property to an HTML element. The two examples above use only a single option: the "value" binding handler.


2 Answers

You can use the css binding to add and remove a class based on the truthiness of a value, but it sounds like your viewModelProperty is the name of a class rather than a boolean.

You can use the attr binding with the static class included like: (attr: { 'class': 'staticClassName ' + viewModelPropertyValue } or (viewModelPropertyValue() if it is an observable).

Otherwise, there is a community binding here that will add and remove a class in the manner that you are after: https://github.com/SteveSanderson/knockout/wiki/Bindings---class

like image 53
RP Niemeyer Avatar answered Oct 13 '22 00:10

RP Niemeyer


In Knockout 2.2.0, you can!

<span class='staticClassName' data-bind='css: viewModelPropertyValue'></span>

like image 24
Jonatan Littke Avatar answered Oct 13 '22 00:10

Jonatan Littke