我已经找到了一些关于此的答案,但无法将它们放在一起。第一天使用 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)") ▲
p.dislikeButtonMessage(bind-data="click=voteComment(id, false)") ▼
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">▲</p>
<p bind-data="click=voteComment(id, false)" class="dislikeButtonMessage">▼</p>
</div>
<p data-bind="text: score" class="messageScore"></p>
</div>
</div>
</div>
它提示 text 不是函数,而这正是我希望它能够找到的属性。我该如何解决这个问题?
最佳答案
如果您更正了拼写错误,您的代码应该可以正常工作。 forEach
应为 foreach
,bind-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/