2016-11-11 151 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我更新了答案和視圖 –