Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine knockout data-bind: text with hard-coded string?

I want to combine a knockout data-bind: text with a hard coded text like the example below:

<h6 data-bind="text: username + 'are now logged in'"></h6>

I have tried several different pluses and semicolons etc but couldn't make it work.

like image 260
SLI Avatar asked Feb 11 '16 09:02

SLI


1 Answers

You need to execute observables to get their value:

ko.applyBindings({ username: ko.observable("johndoe") });
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<h6 data-bind="text: username() + 'are now logged in'"></h6>

Better is though to use a (pure)Computed observable, which you can unit test:

function ViewModel() {
  var self = this;
  self.username = ko.observable("johndoe");
  self.loggedInMessage = ko.pureComputed(function(){
    return self.username() + " is now logged in";
  });
}

ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<h6 data-bind="text: loggedInMessage"></h6>
like image 194
Jeroen Avatar answered Sep 18 '22 01:09

Jeroen