0

Say I have an element in my template like the following:

<div class="c1 c2 c3"></div>

It has several classes applied to it, but at design time I won't know exactly what classes they are.

If the model used for data binding/linking has a property called x that is true, then I would like to add an additional class to the <div>, let's call it c4, otherwise I would want to remove c4 and keep the existing classes intact.

How can this be done using jsViews?

CHS
  • 965
  • 2
  • 18
  • 29

2 Answers2

4

There are some new samples that cover CSS and class binding - and which show some new built-in support for toggling a class. So it should be a lot easier now...

In fact there is a tutorial sequence on data-linking, which includes this page on data-linking class, and this one specifically on toggling class.

In your case, you would write:

<div class="c1 c2 c3" data-link="class{merge:x toggle='c4'}">
BorisMoore
  • 8,444
  • 1
  • 16
  • 27
1

You could do something like this in a template:

<div class="c1 c2 c3{^{if Properties.x}} c4{{/if}}"></div>

You could also do use a function to return the class value:

<div data-link="class{:~getClass(#data)}"></div>

Register the helper function like below

$.views.helpers({
    getClass: function(data){ //very simple, but you can see how this could be made more powerful by using data properties to determine class
    var myClass = "c1 c2 c3";
    if (data.Properties.x === true){
    myClass+=" c4";
    }
    return myClass;
    }});
Ben
  • 41
  • 5
  • I think those are both good ideas. Do you know if there's a way in the helper function to get access to the div and use jQuery to add/remove the C4 class instead of replacing all the classes? – CHS Sep 18 '13 at 14:43
  • 1
    In fact you can't use the first approach - putting {^{if...}} inside the class attribute value. See http://www.jsviews.com/#samples/data-link/class for an explanation. As to getting access to the div, yes, it is this.linkCtx.elem from code within the helper. But see my answer below for a better approach. – BorisMoore Oct 09 '13 at 01:59