How to concatenate a css class name?

282 views
Skip to first unread message

seank...@gmail.com

unread,
Sep 13, 2012, 3:51:19 PM9/13/12
to knock...@googlegroups.com
[Apologies for the vague first post; most of the information is on the StackOverflow site and I didn't want to duplicate the information/formatting.]

Hi all,

per this StackOverflow question, I'm trying to figure out how to apply a css class name that's concatenated from my ViewModel (or if that's even possible).

Jim G. helpfully responded that he's pretty sure it's not possible to concatenate the name of a CSS class that will change at run-time (per my example in the thread), but I wanted to check here to make doubly sure that it's not possible.

After reviewing the link, any thoughts on this? Thanks in advance for your help!

rpn

unread,
Sep 13, 2012, 4:25:00 PM9/13/12
to knock...@googlegroups.com, seank...@gmail.com
Hi Sean-
One option that you have for this one is to bind a computed observable against the css binding.  Your computed observable would then return an object with the various classes with an appropriate true/false value.

So, you would do something like:

data-bind="css: myClasses"

Then in your view model:

this.myClasses = ko.computed(function() {
  var result = {};

  result["someClass" + this.suffix()] = true;

  return result;
}, this);

You can use any logic that you want in the computed observable.  You just need to return an object that has keys equal to the classes and their value determining whether the class should be added or removed.

This can at least leave you with cleaner markup.
Reply all
Reply to author
Forward
0 new messages