I've built a simple backbone application, but I'm struggling with a more complex check that needs to be performed.
Below is my code. I'm creating a list of chat participants. Eventually, I'll pass this list into a JavaScript function.
Participant = Backbone.Model.extend({});
Participants = Backbone.Collection.extend({
model: Participant
});
ParticipantView = Backbone.Marionette.ItemView.extend({
template: "#participant-template",
tagName: 'div',
className: 'call-participant',
initialize: function () {
this.$el.prop("id", this.model.get("chatid") + "-" + this.model.get("participantName"));
},
});
ParticipantsView = Backbone.Marionette.CompositeView.extend({
template: "#participants-template",
tagName: 'div',
itemView: ParticipantView,
appendHtml: function(collectionView, itemView) {
collectionView.$el.append(itemView.el);
}
});
MyApp.addInitializer(function(options)) {
var participantsView = new ParticipantsView({
collection: options.participantNames
});
MyApp.participantContainer.show(participantsView);
var participantsModel = new Participants();
};
$(document).ready(function() {
MyApp.start({participantsModel: participantsModel});
})
The issue I'm facing is that when participants leave or join the chat, the message is resent with a new participant list, potentially missing some participantName values.
So, my question is: How and where do I instruct backbone.marionette to compare the existing models with the new model list for a specific chatid, and remove models that are no longer in the list, while adding new ones?
I construct my ID using chatid and participantName (which is unique as it is the JID without the server part). This ID format helps me differentiate between multiple chat lists on a single page.
Thank you. Feel free to ask for more information if needed. jsFiddle: http://jsfiddle.net/966pG/175/
Warm regards,
Gary Shergill
EDIT: I'm aware of get and set methods, but I am unsure how to utilize them effectively. I've tried referring to the documentation "".
EDIT: Providing a live scenario below. I have a JavaScript function that listens for pubsub events and, upon receiving the relevant event, creates an array of participant objects:
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({"participantName": participant, "chatid": chatid});
}
});
var chatid = $(iq).find('chatid').text();
...
participantsModel.add(new Participants({
chatid : chatid,
participantArray : participants
}))