L. Heider
L. Heider

Reputation: 1819

Knockout JS: CSS binding in foreach

I am trying to create a list of fading (WebSocket-)messages in the style of bootstraps 'alerts': success, info, error ...

<div data-bind="foreach: messages">
  <div class="message" data-dind="css: $parent.foo($data)"> 
  </div>
</div>

Each message should get it's style class dynamic in relation to it's property 'styleClass'.

  var viewModel = {
    messages: ko.observableArray(),

    foo: function(data) {
      return data.styleClass; // could be e.g. 'alert'
    }
  };


  ko.applyBindings(viewModel);

What ist the right practice for this attempt? Is it to use 'pureComputeds'. In fact I tried several other approaches.. However I get no error but no added style class though.

Upvotes: 1

Views: 1014

Answers (1)

Rafael Companhoni
Rafael Companhoni

Reputation: 1790

If you have an observable array of objects and each object defines what css class should be used then you could simply use a css binding:

<div role="alert" data-bind="css: styleClass">

var ViewModel = function () {
    this.messages = ko.observableArray([ 
      { styleClass: "alert alert-success", message: "This is a success message"  },
      { styleClass: "alert alert-warning", message: "This is a warning message"  },
      { styleClass: "alert alert-danger", message: "This is an error message"  }
    ]);
  };

ko.applyBindings(new ViewModel());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div data-bind="foreach: messages">
  <div role="alert" data-bind="css: styleClass">
    <span data-bind="text: message">           
  </div>      
</div>

Upvotes: 4

Related Questions