backbone.js路由器没有响应url片段

时间:2012-06-12 16:55:21

标签: javascript jquery backbone.js

我有一个简单的路由器定义和实例化。

问题:当我转到网址http://localhost/backbone1/#photos/5时,我希望在javascript控制台中看到来自console.log()的输出,但没有显示任何内容。我错过了什么吗?

JS代码

var GalleryRouter = Backbone.Router.extend({

    routes: {
        "about": "showAbout",
        "photos/:id": "getPhoto",
        "search/:query": "searchPhotos",
        "search/:query/p:page": "searchPhotos",
        "photos/:id/download/*imagePath": "downloadPhoto",
        "*other": "defaultRoute"
    },

    showAbout: function() {

    },

    getPhoto: function(id) {
        console.log('You are trying to reach photo ' + id);
    },

    searchPhotos: function(query, page) {
        console.log('Page number: ' + page + ' of the results for ' + query);
    },

    downloadPhoto: function(id, imagePath) {

    },

    defaultRoute: function(other) {
        console.log("Invalid. You attempted to reach: " + other);
    }



});

var myGalleryRouter = new GalleryRouter();

2 个答案:

答案 0 :(得分:1)

您缺少初始化方法

    var initialize = function () {
            var myGalleryRouter = new GalleryRouter();
            Backbone.history.start();
        };
return {
        initialize: initialize
    };

答案 1 :(得分:0)

在您致电Backbone.history.start()后,路由器开始侦听网址哈希更改。通常,您需要先加载基本数据并初始化全局视图,然后启动路由器。