This problem is going to be hard for me to explain but I will try my best.
When a user clicks a UserView it uses the same model to show a more detailed ProfileView
If the user clicks on more than one UserView and then decides to click on the chat button that is on each ProfileView. Every model that the user has clicked on in the is outputted
So say I have clicked 3 profiles and then I click on the chat button it will output this to the console.
"start chat with >" model1
"start chat with >" model2
"start chat with >" model3
I only want the user that was last clicked on…
Can anyone explain to my why these models are stacking up?
Here is the code that you might need.
UserView which represents each model in my collection.
var UserView = Backbone.View.extend({
tagName: 'li',
className: 'user',
template: $('#tUser').html(),
events: {
'click' : 'clicked'
},
initialize: function() {
this.render();
},
render: function() {
var user = _.template(this.template, this.model.toJSON());
//this.el.html(user);
var show = this.$el.html(user);
$('#users').append(show);
return this;
},
clicked: function() {
new ProfileView({model: this.model});
}
});
As you can see I have set up a click event when a UserView is clicked and then it instantiates a ProfileView using the current model.
var ProfileView = Backbone.View.extend({
el: '#profiles',
template: $('#tProfile').html(),
events: {
'click .chat' : 'startChat'
},
initialize: function() {
_.bindAll(this, 'render');
console.log('profile', this.model.toJSON());
this.render();
},
render: function() {
var user = this.model.toJSON();
var profile = _.template(this.template, this.model.toJSON());
var show = this.$el.html(profile);
return this;
},
startChat: function() {
console.log("start chat with", this.model.toJSON());
}
});
Unless you plan on having more than one profile view visible on the screen at any given time, you should convert your profileView into a singleton.
Your UserView first checks if it has an assigned profile, and simply updates the model if so:
ProfileView no longer renders on instantiation: