如何为骨干路由构建动态URL?

时间:2013-12-10 11:06:16

标签: javascript jquery html5 backbone.js url-routing

我这里有复杂的路由。构建子视图的URL以导航不同的父视图。

domain.com/categories/1/details  
domain.com/categories/1/price  
domain.com/categories/1/owner

domain.com/categories/2/details  
domain.com/categories/2/price  
domain.com/categories/2/owner

我需要为详细信息,价格和所有者视图构建网址。

<a href="#/categories/id/price">Price</a>
<a href="#/categories/id/details">details</a>
<a href="#/categories/id/owner">owner</a>

需要动态替换id!

我如何构建它们?

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

var myRouter = Backbone.Router.extend({
          routes : {}
    });
    myRouter.on('route:categories/:id/details' function() {

    });

    myRouter.on('route:categories/:id/price' function() {

    });

    myRouter.on('route:categories/:id/owner' function() {

    });

答案 1 :(得分:0)

在您的视图模板中,您将拥有:

<script type="text/template" id="my-template">
    <a href="#/categories/<%= id %>/price">Price</a>
    <a href="#/categories/<%= id %>/details">details</a>
    <a href="#/categories/<%= id %>/owner">owner</a>
</script>

然后在视图的渲染方法中,您只需要传入id变量。

<script type="text/javascript">
    var userId = 42;

    var MyView = Backbone.View.extend({
        initialize: function(){
            this.render();
        },
        render: function(){
            // Compile the template using underscore
            var template = _.template( $("#my-template").html(), {id: userId});

            // Load the compiled HTML into the Backbone "el"
            this.$el.html( template );
        }
    });
</script>

以下是关于可能有用的主题的更多内容:http://backbonetutorials.com/what-is-a-view/