2013-04-03 107 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