1

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.

1
  • Could you try to edit the question and extend it into a minimal reproducible example? Though not necessarily idiomatic, your solution could work in theory, but it's impossible to tell with just what you posted... Commented Feb 26, 2017 at 20:59

1 Answer 1

4

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>

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.