主干子路由器到特定视图

Backbone Subrouter to specific view

本文关键字:视图 路由器      更新时间:2023-09-26

是否可以将子路由器添加到特定视图?假设我有一个适用于多辆汽车的骨干应用程序。现在,我的路由器看起来像这样

carRouter = Backbone.Router.extend({
   routes: {
      '': 'index'
      'contact' : 'contact'
      ':car': 'car',
      ':car/gallery' : 'cargallery',
      ':car/specs' : 'specs',
      ':car/infos' : 'infos',
      'about: 'aboutPage'
    }
    car: function(){
       // do this
    },
    cargallery: function(){
       // do this
    },
    specs: function(){
       // do this
    },
    infos: function(){
       // do this
    }
    ...etc
});

这种方法显然使整个页面呈现,我基本上想要避免这种情况。例如,当我来回单击"图库"和"规格"时,每次单击时整个页面都会重新呈现。

那么,是否可以执行以下操作:

routes: {
      'contact' : 'contact'
      ':car': 'car',
      'about: 'aboutPage'
      },
     car: function(){
         // new router containing
         // ':car/gallery' : 'cargallery',
         // ':car/specs' : 'specs',
         // ':car/infos' : 'infos',
     },
  }
然后,在汽车

页面上,我将在菜单中有 3 个选项卡(图库、规格、信息),这些选项卡将加载特定汽车的模型/集合,而无需重新渲染页面?

任何帮助/建议不胜感激!

您可以使用事件,主干触发器和自定义事件处理程序对象来实现此目的。

CarView 中的事件哈希

events : {
    "click .spec" : "showSpecs",
    "click .gallery" : "showGallery",
    "click .info" : "showInfo",
},
//Invoked when you click the show specs tab.
showSpecs : function(event) {
//Say that EventBus is your custom event handler
    event.preventDefault();
    MyApp.EventBus.trigger("show:spec",payload); 
},
showGallery : function(event) {
    event.preventDefault();
    MyApp.EventBus.trigger("show:gallery",payload); 
}
....

在MyApp.EventBus中:

_.extend(MyApp.EventBus,Backbone.Events);  
MyApp.EventBus.showGallery = function(payload) {
  // payload is an optional data that you can get from the triggered view
  // Fetch your models or collection
  // Instantiate the corresponding view and pass your data(models/collections) to it.
  // Update the url to reflect the new view so that if you hit refresh you
  // come to the same tab.
  MyApp.router.navigate("/your-url",{trigger:false});
}
MyApp.EventBus.on("show:gallery",showGallery);

还要在路由器中添加一个可以处理选项卡刷新的方法。