2013-10-10 26 views
3

我沿着Organizing Backbone Using Modules tutorial进行跟踪,除了自文章写入以来为适应对依赖项的更改所做的一些调整之外,我无法让我的.on()事件在匹配路由时触发。无法获取Backbone.js路由处理程序以在匹配路径上触发

如果你看看索引路由器,你会看到一个alert和一个console.log()。页面加载时也不会触发。也没有js错误。

任何帮助将不胜感激。

router.js

define([ 
    'jquery', 
    'underscore', 
    'backbone', 
    'views/index', 
    'views/ideas' 
], function($, _, Backbone, IndexView, IdeasView) { 

    var AppRouter = Backbone.Router.extend({ 
    '': 'index', 
    '/ideas': 'showIdeas', 
    '*actions': 'defaultAction' 
    }); 

    var initialize = function() { 

    console.log('this works so i know initialize() is being called'); 

    var app_router = new AppRouter; 

    // not firing 
    app_router.on('route:index', function() { 
     alert('hi'); 
     console.log('hi'); 
     // var index_view = new IndexView(); 
     // index_view.render(); 
    }); 

    // not firing 
    app_router.on('route:showIdeas', function() { 
     console.log('showIdeas'); 
     var ideas_view = new IdeasView(); 
    }); 

    //not firing 
    app_router.on('route:defaultAction', function(actions) { 
     console.log('No route:', actions); 
    }); 

    if (!Backbone.history.started) { 
     Backbone.history.start(); 
     console.log("Route is " + Backbone.history.fragment); 
    } 
    }; 

    return { 
    initialize: initialize 
    }; 
}); 
+0

什么是一个没有触发你的路线的网址的例子? – kinakuta

+0

刚刚/或更具体地说,http://0.0.0.0:3000/ – doremi

回答

1

确保你把你的实际路线的路线哈希在路由器上定义:

var AppRouter = Backbone.Router.extend({ 
    routes: { 
     '': 'index', 
     '/ideas': 'showIdeas', 
     '*actions': 'defaultAction' 
    } 
}); 

我还想补充一点,我更愿意把回调对于路由器定义中的路由(它只是一个首选项):

var AppRouter = Backbone.Router.extend({ 
    routes: { 
     '': 'index', 
     '/ideas': 'showIdeas', 
     '*actions': 'defaultAction' 
    }, 

    index: function() { 
     // function body here 
    }, 

    showIdeas: function() { 
     // function body here 
    }, 

    defaultAction: function() { 
     // function body here 
    } 
}); 

这不是必需的,但对我来说,阅读和查看正在发生的事情更容易。

+0

啊,完全错过了。很好的接收。谢谢! – doremi

相关问题