如何结合knockout数据绑定:文本与硬编码字符串?

时间:2016-02-11 09:58:15

标签: html knockout.js

我想将淘汰赛data-bind: text与硬编码文本结合起来,如下例所示:

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

我尝试了几种不同的加号和分号等,但无法使其正常工作。

1 个答案:

答案 0 :(得分:8)

您需要执行observable来获取它们的值:

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>

更好的是使用(纯)Computed observable,你可以单元测试:

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>