【问题标题】:Dynamically create backbone routes动态创建骨干路由
【发布时间】:2013-04-03 14:02:56
【问题描述】:

这是我的主干路由器:

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(route:about)..." 避免递归呢?

【问题讨论】:

    标签: backbone.js backbone-routing


    【解决方案1】:

    使用这些路线:

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

    并删除 initRoutes。这应该可以正常工作。

    【讨论】:

    • 邪恶! Tnx 兄弟,这些天你真的在帮助我:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-31
    相关资源
    最近更新 更多