2013-10-10 25 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

相關問題