2014-07-18 71 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(); 
    } 
});