我正在研究以下功能:当用户单击页面上的某张照片时,将出现一个模型modalView
,其中包含该项目的更多详细信息。在modalView
中,用户可以点击另一个项目的照片,这将关闭第一个模态窗口modalView
并打开一个新的模态窗口modalView
,其中包含这个下一个项目的全部细节。路由器功能处理modalView
的打开和关闭。删除第一个视图并创建第二个视图(backbone.js)
(用户可能会遇到闪烁,但那是另一个问题)
问题:当用户点击内modalView
另一个项目的照片,showModal()
将使当前modalView
关闭和网址更新为下一个项目/product/1234
,但新的modalView
未显示!使用console.log()
进行调试,我发现第一个modalView
关闭,第二个modalView
打开然后关闭!
发生了什么,以及如何解决这个问题?
路由器
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: '/'
});
查看
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输出
creating new
<----clicks on another photo
closing
creating new
IS两次射击或只是'closeModal'方法的路线?无论如何,而不是关闭模式和重新开放你试着只是交换视图模型(类似于'app.modelView.model = new Product({id:id}); app.ModelView.model.fetch();') – Jack
' closeModal'方法似乎被触发两次,一次关闭第一个视图,一次创建第二个视图后关闭第二个视图。我会研究你的建议:) – Nyxynyx
我试着重新创建你的例子的简化版本,'closeModal'方法只是(正确)发射一次。 – Jack