【问题标题】:Backbone router with multiple parameters具有多个参数的骨干路由器
【发布时间】:2013-11-27 11:08:24
【问题描述】:

我需要让它工作:

routes: {
  ':product' : 'showProduct',
  ':product/:detail': 'showProductDetail'

showProductDetail 在设置 ':product' 路由时永远不会被调用,即使它是在之后设置的。我尝试了以下

routes: {
  ':product(/:detail)': showProductOrDetail
}

但是当只有第二个参数改变时,这不会被调用。 重要的是我有产品本身或 url 中的产品和详细信息

有谁知道如何解决这个问题?

【问题讨论】:

    标签: javascript url backbone.js router hashtag


    【解决方案1】:

    您的问题有一个小技巧。我觉得有一种更好的方法可以做到这一点,但应该可以:

    routes: {
        "product/:id": "showProduct",
        "product/:id/details/:did": "showDetails"
    },
    
    showProduct: function(id) {
        this.showDetails(id);
    },
    
    showDetails: function(id, did) {
        // Check did for undefined
    
    }
    

    【讨论】:

    • 在这种情况下,您的方法会奏效,但正如我所说,我也希望在第二条路线中使用产品,因此我可以执行以下操作:mywebsite.com/#category/1/product/3 /detail/1
    • 如果我只调用 mywebsite/com/#product/1 这行不通吗?
    • 如果我感谢@SzymonDrosdzol +1 不会伤害我 ;)
    【解决方案2】:

    延迟响应(超过一年).. 但您可以在骨干路由器中使用 RegEx 来实现此目的。 我的示例假定参数将以数字开头。

    即:localhost:8888/#root/1param/2param

    var router = Backbone.Router.extend({
        initialize: function () {
            // Use REGEX to get multiple parameters
            this.route(/root/, 'page0'); 
            this.route(/root\/(\d+\S+)/, 'page1'); 
            this.route(/root\/(\d+\S+)\/(\d+\S+)/, 'page2');
        },
        page0:function(){
            console.log("no id");
        },
        page1:function(id1){
            console.log(id1);
        },
        page2:function(id1,id2){
            console.log(id1);
            console.log(id2);
        }
    });
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-18
      • 2015-02-26
      相关资源
      最近更新 更多