无法使牵线木偶路由器工作

时间:2014-07-16 11:57:11

标签: javascript backbone.js marionette backbone-routing

我很难让木偶的路由器工作,恰好是路由器的控制器。 这是我的代码:

 App.RouterController = Marionette.Controller.extend({
            render: function(){
                alert(123);
            }
    }); 

//Router
App.Router = Backbone.Marionette.AppRouter.extend({
    appRoutes: {
      "*actions": "render"
    },      
    controller: new App.RouterController,   

    initialize: function(){

        var self = this;
        Backbone.history = Backbone.history || new Backbone.History({});
        var root = "/";

        Backbone.history.start({
            pushState: Modernizr.history,
            root: root,
            silent: !Modernizr.history
        }); 

        // handle history for old internet explorer + normal behaviour
        if(!Modernizr.history) {
            var rootLength = Backbone.history.options.root.length;
            var fragment = window.location.pathname.substr(rootLength) || 'cs';
            self.navigate(fragment, { trigger: true });
        }
    }

});

App.on('start', function(options) {
        App.Main = new App.Main;
        App.Router = new App.Router();
});
App.start();

我期待App.RouterControler的渲染方法将在所有路由上执行,但没有任何事情发生,即使控制台中没有错误显示...... 我做错了什么?

注意:路由器的Initialize方法正常,如果我把警报或控制台登录,它会显示

1 个答案:

答案 0 :(得分:0)

应该初始化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 */
  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();
    } 
});