如何构造用于骨干路由的动态url

how to construct dynamic urls for backbone routing?

本文关键字:动态 url 路由 何构造 用于      更新时间:2024-05-25

这里有复杂的路由。为子视图构建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

我需要构建详细信息、价格和所有者视图的url。

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

需要动态替换id!

我该如何构建它们?

你可以试试这个:

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() {
    });

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

<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/