Vovan_Super
Vovan_Super

Reputation: 515

How to properly apply KO binding the following example

Basicaly, I have viewModel in KO having array of 2 values, I need to change css class prop of element (main) when <a> elemets are being clicked (when 1st li>a "Val1" clicked, <main class="stl1">... and so on). Strangely , nothing happends to <main>:

<script>
        var mainViewModel = function () {
            var self = this;

            self.classArr = ['stl1', 'stl2'];
            self.cssUsed = ko.observable(0);

            self.getClass = function ( data, event ) {
                var dat = event.target.value;
                self.cssUsed = self.classArr[dat];
                console.log( dat + ' : ' + self.cssUsed );
            }

        }
        ko.applyBindings( new mainViewModel() );
</script>    

<div class='page'>
    <header>
       <nav>
         <ul >
           <li><a href="#" data-bind="value: 0, click: getClass">Val1</a></li>
           <li><a href="#" data-bind="value: 1, click: getClass">Val2</a></li>
         </ul>

      </nav>
   </header>

  <div id='maincontent'>
          <main data-bind="css: cssUsed" >
              <div class="center"></div>
          </main>
  </div>
</div>

Upvotes: 0

Views: 34

Answers (1)

acontell
acontell

Reputation: 6932

You got it almost right. The problem was that your were assigning the value in the wrong way. Instead of

self.cssUsed = self.classArr[dat];

try

self.cssUsed(self.classArr[dat]);

Check it out here

Upvotes: 1

Related Questions