2013-04-03 73 views
2

这里是我的骨干路由器:动态创建骨干线路

var Router = Backbone.Router.extend({ 
    routes: { 
     "": "home", 
     "home": "home", 
     "about": "about", 
     "works": "works", 
     "work/:id" : "work", 
     "news": "news", 
     "contact": "contact" 
    }, 

    initRoutes: function(e) {  
     this.on('route:home', function() { 
      page.activepage = "home"; 
      page.render(); 
     }); 
     this.on('route:about', function() { 
      page.activepage = "about"; 
      page.render(); 
     }); 
     this.on('route:works', function() { 
      page.activepage = "works"; 
      page.render(); 
     }); 
     this.on('route:work', function(id) { 
      page.activepage = "works"; 
      page.param = id; 
      page.render(); 
     }); 
     this.on('route:news', function() { 
      page.activepage = "news"; 
      page.render(); 
     }); 
     this.on('route:contact', function() { 
      page.activepage = "contact"; 
      page.render(); 
     }); 
    }, 
    initialize: function(){ 
     var self = this; 
     Backbone.history = Backbone.history || new Backbone.History({}); 
     root = "kitchenV3/"+lang; 
     var enablePushState = true; 
     var pushState = !! (enablePushState && window.history && window.history.pushState); 
     Backbone.history.start({ 
      pushState: pushState, 
      root: root 
     }); 
     self.initRoutes(); 
    } 
}); 

因此,大家可以看到我所有的路线基本上都是做同样的事情(取决于路线名称和参数呈现内容)。因此,如何改写,, this.on(路线:约)...”,以避免递归

回答

9

使用这些路由:?

routes: { 
    '': 'myFunc', 
    ':mod(/)': 'myFunc', 
    ':mod/:id(/)': 'myFunc' 
}, 
myFunc: function(mod, id) { 
    page.activepage = mod || 'home'; 
    if(id) page.param = id; 
    page.render(); 
} 

和删除initRoutes这应该做工精细

+0

妖兽。 !Tnx兄弟,你真的帮我这几天:) – hjuster

+0

是的,我以为我已经看到这个代码的地方x)。 – Loamhoof