I am working on the following feature: When a user clicks on a photo on the page, a modal modalView appears with more details of that item. In modalView, the user can click on the photo of another item, which will close the first modal window modalView and open a new modal window modalView containing full details of this next item. The opening and closing of modalViews are handled by the router functions.
(the user may experience a flicker, but thats another problem)
Problem: When the user clicks on the photo of another item within modalView, showModal() will cause the current modalView to close and the URL updates to that of the next item /product/1234, but the new modalView does not appear! Using console.log() to debug, I found that the first modalView closes, the 2nd modalView opens then closes!
What has happened, and how can this be fixed?
Router
var AppRouter = Backbone.Router.extend({
routes: {,
'product/:id': 'showModal'
},
showModal: function(id) {
// Close any existing ModalView
if(app.modalView) {
app.modalView.closeModal();
console.log('closing');
}
// Create new ModalView
app.modalView = new ModalView({ model: new Product({id:id}) });
console.log('creating new');
}
});
app = new AppRouter();
Backbone.history.start({
pushState: true,
root: '/'
});
View
ModalView = Backbone.View.extend({
el: $('#modal'),
template: _.template( $('#tpl_modal').html() ),
events: {
'click .more_photo': 'showModal',
},
initialize: function() {
// Update Model with Full details
var self = this;
this.model.fetch({
data: {post_id: self.model.get('id')},
processData: true,
success: function() {
self.render();
});
},
render: function() {
$(this.el).show().append( this.template( this.model.toJSON( this.model ) ) );
},
closeModal: function() {
// Restore scrollbars
$(this.el).css('overflow-y', 'auto');
$('body').removeClass('noscroll');
// Close modal and remove contents
$(this.el).fadeOut();
$(this.el).empty();
},
showModal: function() {
// Update URL & Trigger Router function `showModal`
app.navigate('/product/' + this.model.get('id'), {trigger:true});
}
});
Console.log Output
creating new
<----clicks on another photo
closing
creating new
Based on the code you provided I’m not sure why your
closeModalmethod might be firing twice, I’ve created a simplified version off of your code and the method was only called once each time (of course I improvised a bit so maybe that had something to do with it).As an alternative to closing your and reopening your modal view each time you might want to try just swapping the model.
For example