2012-09-05 135 views
3

我正在研究以下功能:当用户单击页面上的某张照片时,将出现一个模型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 
+0

IS两次射击或只是'closeModal'方法的路线?无论如何,而不是关闭模式和重新开放你试着只是交换视图模型(类似于'app.modelView.model = new Product({id:id}); app.ModelView.model.fetch();') – Jack

+0

' closeModal'方法似乎被触发两次,一次关闭第一个视图,一次创建第二个视图后关闭第二个视图。我会研究你的建议:) – Nyxynyx

+0

我试着重新创建你的例子的简化版本,'closeModal'方法只是(正确)发射一次。 – Jack

回答

0

根据你的代码公关ovided我不知道为什么你的方法可能会发射两次,我已经创建了一个简化版本的代码,并且每次只调用一次该方法(当然,我即兴创作了一下,所以也许这与某些事情有关它)。

作为关闭和重新打开模态视图的替代方法,每次您可能想尝试交换模型。

例如

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}) }); 
     } 
    } 
相关问题