我正在开发以下功能:当用户单击页面上的照片时,会出现一个模式modalView
,其中包含该项目的更多详细信息。在 modalView
中,用户可以点击另一个项目的照片,这将关闭第一个模态窗口 modalView
并打开一个新的模态窗口 modalView
包含下一项的完整详细信息。 modalView
的打开和关闭由路由器函数处理。
(用户可能会遇到闪烁,但那是另一个问题)
问题:当用户点击modalView
内另一个项目的照片时,showModal()
会导致当前modalView
关闭,URL 更新为下一个项目 /product/1234
的 URL,但新的 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
最佳答案
根据您提供的代码,我不确定为什么您的 closeModal
方法可能会触发两次,我已经根据您的代码创建了一个简化版本,并且该方法每次仅调用一次(当然我临时做了一点,所以也许这与它有关)。
作为每次关闭并重新打开模态视图的替代方案,您可能想尝试仅交换模型。
例如
showModal: function(id) {
if(app.modalView) {
app.modalView.model = new Product({id:id});
app.modalView.model.fetch();
} else {
app.modalView = new ModalView({ model: new Product({id:id}) });
}
}
关于javascript - 删除第一个 View 并创建第二个 View (backbone.js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12281749/