2013-02-20 70 views
3

我的應用程序有一個主要的地區和某些時候會出現在主要區域子區域,應該是通過URL訪問。主要區域內容由app知道主要區域的功能改變。但是,子視圖中的臨時區域是什麼?Backbone.Marionette更改地區

因此,例如URL /docs將顯示的鏈接列表文件和/doc/:id應顯示在列表旁邊的文檔的內容。那麼/doc/:id如何在某些人在列表中點擊時呈現內容,並在某些人在新標籤中打開網址時呈現列表和內容。

至於我可以看到有有每一個區域的路由器,或與路線和區域應該改變區域經理火災事件的兩個選項。任何提示,以解決這個問題的最佳途徑。

回答

4

好吧,我想出了一個路由器爲每一個區域的解決方案。路由器可以通過路由和視圖的地圖輕鬆配置。當有匹配的路線時,最初傳遞的區域將顯示一個新的視圖實例。

Here是,在此路由參數將傳遞到查看路由器的高級版本。

更新

只有上述解決方案的工作,只要每一個路由只登記一次。如果您第二次註冊相同的路線,第一個路線的回叫將被覆蓋。因此,我想出了一個解決方案,區域控制器不是直接在路由器上註冊路由,而是在全局事件總線(Marionette.Application.vent)上收聽route:change事件,並且路由器在此事件總線上觸發route:change事件。

RouterController:

// The problem with backbone router is that it can only register one function per route 
// to overcome this problem every module can register routes on the RouterController 
// the router will just trigger an event on the `app.vent` event bus when ever a registered routes match 
define(function() { 

    function RouterController(vent) { 
    this.vent = vent; 
    this.router = new Backbone.Router(); 
    } 

    RouterController.prototype = _.extend({ 
     //just pass the route that change you wanna listen to 
     addRoutes: function(routes) { 
     _.each(routes, function(route) { 
      this.router.route(
      route, 
      _.uniqueId('e'), 
      //create a closure of vent.trigger, so when ever the route match it simply trigger an event passing the route 
//   _.partial(_.bind(this.vent.trigger, this.vent), 'route:change', route) 
      _.bind(function() { 
       this.vent.trigger.apply(this.vent, ['route:change', route].concat(_.toArray(arguments))); 
      }, this) 
     ); 
     }, this); 

     } 
    }, 
    Backbone.Events); 

    return RouterController; 
}); 

RegionRouter:

define(['common/App'], function(app) { 

    function RegionRouter(region, routerSettings) { 
     app.router.addRoutes(_.keys(routerSettings)); 

     this.listenTo(app.vent, 'route:change', function() { 
     var route = arguments[0]; 
     var View = routerSettings[route]; 

     if (!View) { 
      return; 
     } 

     var params; 

     if (arguments.length > 1) { 
      params = computeParams(arguments, route); 
     } 
     region.show(new View(params)); 
     }); 
    } 

    RegionRouter.prototype = _.extend(
     { 
     onClose: function() { 
      this.stopListening(app.vent); 
     } 
     }, Backbone.Events 
    ); 

    function computeParams(args, route) { 
     args = Array.prototype.slice.call(args, 1); 

     //map the route params to the name in route so /someroute/:somevalue will become {somevalue: passedArgs} 
     //this object will be passed under the parameter key of the options 
     var params = {}; 
     var regEx = /(?::)(\w+)/g; 
     var match = regEx.exec(route); 
     var count = 0; 
     while (match) { 
     params[match[1]] = args[count++]; 
     match = regEx.exec(route); 
     } 

     return {params: params}; 
    } 

    return RegionRouter; 
    } 
);