简体   繁体   English

在主干模型中将数组呈现为列表

[英]Rendering an Array as a List within a Backbone model

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. 我很难理解这一点(我以前从未使用过下划线),所以我认为最好发布一个与此有关的新话题。

Scenario 情境

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. 我需要将该列表显示为正在渲染的模型的一部分。

Code

Creating the participants array 创建参与者数组

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
    ...
});

The ItemView 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"));
    },

    ...

The template being used 使用的模板

    <script type="text/template" id="template-groupchat">

        <a id='close-<%= chatid %>' class='close hide' data-dismiss='alert' href='#'>
            &times;
        </a>
        ...
        <div class='row' id='row-participants-<%= chatid %>' style='display: none'>
        <!-- CUSTOM CODE SHOULD BE HERE? My attempt:
            <% _.each(participants, function () { %>
                 <%= name %>
            <% }); %>
        -->
        </div>

    </script>

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. 我不确定原始文章中我做错了什么,我认为我将participants数组错误地传递给了underscore.each()部分。

I feel like one of the issues is that you do not pass any arguments to _.each method. 我觉得问题之一是您没有将任何参数传递给_.each方法。

<% _.each(participants, function (participant) { %>
   <%= participant.name %>
<% }); %>

Hope it will fix your problem. 希望它能解决您的问题。

The correct way of using _.each function will be : 使用_.each函数的正确方法是:

<% _.each(participants, function (element,index) { %>
           <%= element.name %>
<% }); %> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM