2016-11-11 195 views
0

下面是我的弹簧mvc上的路由器配置。路由器上的URL参数映射

我的问题是如何将参数与路由器url进行映射,因此当有人通过粘贴或刷新导航到网址时,它将呈现确切的页面。

URL示例:http://localhost:8080/techtalks/#/viewMore/12345

publicRouter.js

define(['jquery', 'underscore', 'backbone', 
    'views/publicModule/viewMoreView', 
], function($, _, Backbone, 
    ViewMoreView 
) { 

    var AppRouter = Backbone.Router.extend({ 
     routes: { 
      // Define some URL routes 
      'viewMore': 'viewMoreView', 
      // Default 
      '*actions': 'defaultAction' 
     } 
    }); 
    var initialize = function() { 
     var app_router = new AppRouter; 
     app_router.on('route:viewMoreView', function() { 
      // Call render on the module we loaded in via the dependency array 
      ViewMoreView.render(); 
     }); 
     Backbone.history.start(); 
    }; 
    return { 
     initialize: initialize 
    }; 
}); 

骨干视图

define(['jquery', 'underscore', 'backbone', 
    'text!../../../viewMore.html' 
], function($, _, Backbone, adminHomeTemplate) { 
    var ViewMoreView = Backbone.View.extend({ 
     publicArticleTbl: null, 
     el: $("#publicPanel"), 
     render: function() { 
      var data = {}; 
      publicArticleTbl = null; 
      // template 
      var compiledTemplateAdminHome = _.template(
       adminHomeTemplate, data); 
      // append the item to the view's target 
      this.$el.html(compiledTemplateAdminHome); 
     }, 
     // Event Handlers 
     events: { 

     }, 
    }); 
    return new ViewMoreView; 
}); 

回答

1

使用回调直接,没有必要使用路由器事件。

此外,从网址捕捉id帕拉姆。

var AppRouter = Backbone.Router.extend({ 
    routes : { 
     // the order the routes are defined is important, any route defined 
     // later takes precedence on previous routes. 

     // Default 
     '*actions' : 'defaultAction' 
     // Define some URL routes 
     'viewMore/:id':'viewMoreView', 
    }, 

    viewMoreView: function(id){ 
     var view = new ViewMoreView({ 
      el: $("#publicPanel"), 
      id: id 
     }); 
     view.render(); 
    } 
}); 
var initialize = function() { 
    var app_router = new AppRouter(); 
    Backbone.history.start(); 
}; 

,那么该观点:

var ViewMoreView = Backbone.View.extend({ 
    // compile the template once 
    template: _.template(adminHomeTemplate), 

    initialize: function(options) { 
     // make a copy of the options 
     this.options = _.extend({ 
      /* default options goes here if any */ 
     }, options); 

     console.log("id:", this.options.id); 
    }, 
    render: function() { 
     var data = {}; 

     // use the compiled template function here 
     this.$el.html(this.template(data)); 
     return this; 
    }, 
}); 

骨干工程与标准的链接,没有必要有花哨的东西叫的路线。

'<a href="#/viewMore/' + item['id'] + '" >Read more</a>' 

制作模块时,通常返回构造函数而不是实例。这有助于重用相同的视图类型。当模块是全球服务时返回实例。

+0

为什么你爱骨干emile – Mahi

+0

我如何在视图中获得'id'。 – boycod3

+0

@ boycod3我更新了答案和视图 –