Question

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

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.

Was it helpful?

Solution

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.

OTHER TIPS

The correct way of using _.each function will be :

<% _.each(participants, function (element,index) { %>
           <%= element.name %>
<% }); %> 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top