2014-07-18 73 views
1

我想在我的backbone.Marionette應用中設置路由,我是Backbone的新手。Backbone Marionette路由問題

我有JS喜歡

var firstProject= new Marionette.Application(); 

firstProject.addRegions({ 
    main : 'main', 
}); 

//my router 
var MyRouter = Backbone.Marionette.AppRouter.extend({ 
    // "someMethod" must exist at controller.someMethod 
    appRoutes: { 
    "first" : "someOtherMethod" 
    }, 

    /* standard routes can be mixed with appRoutes/Controllers above */ 
    routes : { 
    "second" : "someOtherMethod" 
    }, 
    someOtherMethod : function(){ 
     alert('hi') 
    } 
}); 


firstProject.on('initialize:after', function(){ 
    if(Backbone.history){ 
     Backbone.history.start(); 

    } 
}); 
在我的HTML

,我有

<a href="#/first" class="btn btn-primary btn-lg" role="button">First product</a> 
<a href="#/second" class="btn btn-primary btn-lg" role="button">First product</a> 

我想瀏覽我的網頁加載我的第一個HTML頁面和第二html頁面,當我點擊的鏈接。我已經閱讀過文檔,但它們有點複雜。有人可以給我一個暗示嗎?非常感謝!

+0

嘗試取/出'href'。只要使用'#first'和'#second' –

+0

你確定你想要你的主區域選擇器是'main'嗎?你的意思是'.main'還是'#main'? –

回答

1

路由您的應用的最簡單形式是使用AppRouter的屬性「路由」,如下所示。

var firstProject= new Marionette.Application(); 

firstProject.addRegions({ 
    main : 'main', 
}); 

//my router 
var MyRouter = Backbone.Marionette.AppRouter.extend({ 

    /* standard routes can be mixed with appRoutes/Controllers above */ 
    routes : { 
    "second" : "secondMethodFromThisObject", 
    "first" : "firstMethodFromThisObject" 
    }, 
    firstMethodFromThisObject : function(){ 
     alert('hi'); 
    }, 
    secondMethodFromThisObject : function(){ 
     alert('hi'); 
    } 
}); 


firstProject.on('initialize:after', function(){ 
    if(Backbone.history){ 
     Backbone.history.start(); 
    } 
}); 

如果您想要使用appRoutes屬性,就像您通常會在應用程序較大時一樣。你會像下面這樣更好。

var firstProject= new Marionette.Application(); 

firstProject.addRegions({ 
    main : 'main', 
}); 

//my router 
var MyRouter = Backbone.Marionette.AppRouter.extend({ 

    /* standard routes can be mixed with appRoutes/Controllers above */ 
    appRoutes : { 
    "first" : "firstMethodFromController", 
    "second" : "secondMethodFromController" 
    } 
}); 

var MyController = Marionette.Controller.extend({ 
    "secondMethodFromController": function() { 
     alert('Hi from inside the controller'); 
    }, 
    "firstMethodFromController": function() { 
     alert('Hi from inside the controller'); 
    } 
}); 

firstProject.addInitializer(function() { 
    // initialize routes with controller 
    new MyRouter({ controller: new MyController }); 
}); 

firstProject.on('initialize:after', function(){ 
    if(Backbone.history){ 
     Backbone.history.start(); 
    } 
});