javascript - forEach 在 KnockoutJS 中具有对象属性

标签 javascript html knockout.js pug

我已经找到了一些关于此的答案,但无法将它们放在一起。第一天使用 Knockout,如果我的想法完全错误,请告诉我!

我想表示我拥有的评论列表。评论包含多个属性,例如 {text: ..., score: ..., ...}

我知道我有一个 View 模型

var MatchupViewModel = function(comments) {
    this.comments = ko.observableArray(comments);
}

ko.applyBindings(new MatchupViewModel(comments), document.getElementById("leftchat"));

我知道 forEach 看起来有点像这样:

  • 在 Jade 中(我正在使用:

#leftchat.chat(data-bind="forEach: comments")
                .fullMessage
                    .content
                        p.textcontent(data-bind="text: text, visible: text")
                        img.imagecontent(data-bind="visible: isImage, attr={src: url}")
                    .scorecontainer
                        .buttonContainer
                            p.likeButtonMessage(bind-data="click=voteComment(id, true)") &#x25B2
                            p.dislikeButtonMessage(bind-data="click=voteComment(id, false)") &#x25BC
                        p.messageScore(data-bind="text: score")

翻译成html:

<div id="leftchat" data-bind="forEach: comments" class="chat">
  <div class="fullMessage">
    <div class="content">
      <p data-bind="text: text, visible: text" class="textcontent"></p><img data-bind="visible: isImage, attr={src: url}" class="imagecontent"/>
    </div>
    <div class="scorecontainer">
      <div class="buttonContainer">
        <p bind-data="click=voteComment(id, true)" class="likeButtonMessage">&#x25B2</p>
        <p bind-data="click=voteComment(id, false)" class="dislikeButtonMessage">&#x25BC</p>
      </div>
      <p data-bind="text: score" class="messageScore"></p>
    </div>
  </div>
</div>

它提示 text 不是函数,而这正是我希望它能够找到的属性。我该如何解决这个问题?

最佳答案

如果您更正了拼写错误,您的代码应该可以正常工作。 forEach 应为 foreachbind-data 应为 data-bind(除非您将其设为自定义绑定(bind)). 看看下面的例子。当 text 为假值(null,空字符串)时,该节点将被隐藏,否则其值将可见。这也适用于 observable 属性。

var m = {
  comments: [
    {text: 'a'},
    {text: ko.observable('') },
    {text: null},
    {text: ko.observable('c')}
  ]
};

ko.applyBindings(m);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div id="leftchat" data-bind="foreach: comments" class="chat">
  <div data-bind="text: text, visible: text" class="textcontent"></div>
</div>

关于javascript - forEach 在 KnockoutJS 中具有对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39668361/

相关文章:

javascript - 对数组进行排序而不重绘内容

javascript - Angular-UI( Bootstrap )弹出窗口不起作用?

javascript - 隐藏 api key ,php

javascript - jQuery 代码无法工作,无法理解标记

HTML/CSS - 居中内联多个 div

ios - 在屏幕锁定的情况下运行 TriggerIO iOS 应用程序?

javascript - 使用 Q 动态运行一系列 Promise

javascript - 如何使用模板中的 Knockout 映射插件映射到来自服务器对象的数组?

javascript - 防止长时间运行的 javascript 锁定浏览器

html - 当用户鼠标悬停在用户名上时如何设计页眉样式显示注销