SLI
SLI

Reputation: 93

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.

Upvotes: 6

Views: 4181

Answers (1)

Jeroen
Jeroen

Reputation: 63830

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>

Upvotes: 10

Related Questions