在主干模型中将数组呈现为列表 [英] Rendering an Array as a List within a Backbone model
问题描述
这是我发现的另一篇文章的扩展: Backbone:A视图内的视图列表
This is an extension to another post I found: Backbone: A list of views inside a view
我很难理解这一点(我以前从未使用过下划线),所以我认为最好发布一个与此有关的新话题.
I had trouble understanding this (I've never used underscore before) so I figured it's best to post a new topic about this.
场景
我有一个创建的群聊模型,该模型列出了各种信息.这包括该群聊中参与者的列表.我需要将该列表显示为正在渲染的模型的一部分.
I have a model of a group chat which is created and lists a variety of information. This includes a list of the participants in that group chat. I need to display that list as part of the model being rendered.
代码
创建参与者数组
var participants = [];
$(iq).find('participants').each(function() {
var participantsNodes = this.childNodes;
for (var i = 0; i < participantsNodes.length; i++) {
var participantAttr = participantsNodes[i].attributes
var participant = participantAttr[0].nodeValue;
participants.push({"name": participant, "chatid": chatid});
}
});
...
model.set({
participants : participants,
chatid : chatid
...
});
ItemView
GroupChatView = Backbone.Marionette.ItemView.extend({
template : "#template-groupchat",
tagName : 'div',
className : 'alert alert-custom',
initialize: function(){
this.$el.prop("id", this.model.get("chatid"));
},
...
正在使用的模板
<script type="text/template" id="template-groupchat">
<a id='close-<%= chatid %>' class='close hide' data-dismiss='alert' href='#'>
×
</a>
...
<div class='row' id='row-participants-<%= chatid %>' style='display: none'>
<!-- CUSTOM CODE SHOULD BE HERE? My attempt:
<% _.each(participants, function () { %>
<%= name %>
<% }); %>
-->
</div>
</script>
这总是返回错误,指出名称"不存在.我不确定原始文章中做错了什么,我认为我将participants
数组错误地传递给了underscore.each()
部分.
This constantly returns an error saying that "name" does not exist. I'm unsure what I'm doing wrong from the original post, I think I'm passing the participants
array incorrectly to the underscore.each()
part.
推荐答案
我觉得问题之一是您没有将任何参数传递给_.each
方法.
I feel like one of the issues is that you do not pass any arguments to _.each
method.
<% _.each(participants, function (participant) { %>
<%= participant.name %>
<% }); %>
希望它可以解决您的问题.
Hope it will fix your problem.
这篇关于在主干模型中将数组呈现为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!