Search code examples
javascriptbackbone.js

How can I test Backbone Router Hashing locally?


What I mean is as I set up a hash route per the cdnjs tutorial it is assumed testing as if the page was hosted somewhere (i.e. mywebsite.com/#/posts/23/) whereas I am current hosting it locally so my address looks something like file:///C:/Folder/index.html.

My question is how do I properly test this hash route using that method. I have tried appending the current filepath like so file:///C:/Folder/index.html/#/posts/23 but this does nothing. Perhaps my code is the main issue; however, it is basically a copy of what is provided by cdnjs. The code works for the initial page (i.e. I get the null action alert by the default route) so I know as much as that working.

Router code:

var AppRouter = Backbone.Router.extend({
    routes: {
        "posts/:id": "getPost",
        "*actions": "defaultRoute"
    }
});

var app_router = new AppRouter;

app_router.on('route:getPost', function(id) {
    alert("get post number " + id);
});

app_router.on('route:defaultRoute', function(actions) {
    alert(actions);
});

Backbone.history.start();

Solution

  • I would suggest using a simple node server to serve the index route.

    try using serve:

    $ npm install -g serve
    

    then you can cd to the proj root directory, and run with:

    $ serve .
    

    by default I think it serves at http://localhost:3000 so you want to point your browser there.

    EDIT

    Short answer is, you need to serve the files with a webserver, what you use is your choice, but as you said, you will be unable to use an absolute file path.