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='#'>
×
</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.
I feel like one of the issues is that you do not pass any arguments to
_.each
method.Hope it will fix your problem.
The correct way of using _.each function will be :