0

I am trying to implement CSS binding in knockoutJS.

I want to print all the names in the names array, One after another. The catch is that there is another array which has some special names.

All the special names should get "good" CSS class. And the rest, "bad" css class.

Here is something that i have tried:

HTML

 <!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery.min.js"></script>
<link href="http://getbootstrap.com/dist/css/bootstrap.css" rel="stylesheet" type="text/css" />
<script src="http://getbootstrap.com/dist/js/bootstrap.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>



  <div data-bind="foreach : items">
    <div data-bind="text: $data, css: checkName($data)" ></div>
  </div>


</body>
</html>

JAVASCRIPT

var dataModel = function(){

  self.items = ko.observableArray(["don","bom","harry","sharry","ron"]);
  self.names = ["ron","harry"];

  self.checkName = ko.observable(function(name){

    if( $.inArray(name,self.names) ){
            return "good";
        }
        else{
            return "bad";
        }
  });

};

ko.applyBindings(new dataModel());

FIDDLE - http://jsbin.com/difaluwo/2/edit

Now its not woking. In console its giving me "Script error. (line 0)"

Thanks !

1 Answer 1

1

The out of the box CSS binding is a little tricky. You specify class name and then the condition when it will be applied.

JSBIN

<div data-bind="foreach : items">
    <div data-bind="text: $data, css: { good: isGoodName($data), bad: !isGoodName($data) }" ></div>
  </div>

And your view model:

var dataModel = function(){

  self.items = ko.observableArray(["don","bom","harry","sharry","ron"]);
  self.names = ["ron","harry"];

  self.isGoodName = function (name) {
    return $.inArray(name, self.names) !== -1;
  };

};

ko.applyBindings(new dataModel());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.