Search code examples
routessammy.js

Sammy routing not working


I'm unable to get sammy.js routing working as expected.

I have the following JavaScript.

(function ($) {

    var app = $.sammy('#main', function () {

        this.get('#/', function (context) {
            context.log("start page");
        });

        this.get("#/another/:id/", function (context) {
            context.log("another page with id = " + context.params["id"]);        
        });
    });

    $(function (context) {
        app.run('#/');
    });

})(jQuery);

My understanding is that whenever the URL has changes, and so long as the new route corresponds to one of the declared routes, then I should see the relevant message in the console log.

But I don't.

When the page first loads I can see the "start page" message. So far so good.

If I then

  • click on a link which points to [my url]/#/another/1/
  • manually type [my url]/#/another/1/ into the address bar and hit <Enter>

... nothing happens, i.e. I don't see the message for the second route.

However, with the second route in the address bar, if I now hit F5 or click the browser's refresh button then the page reloads and shows the expected console message.

Have I misunderstood, or shouldn't Sammy notice when a hyperlink or keyboard has changed the URL hash, and then act accordingly? Is there something else that I need to add to my script?


Solution

  • Each sammy application needs to be attached to a DOM element.

    So you are probably missing the #main element form your page.

    So you need to add a #main element in your DOM somewhere:

    <div id="main">
    </div>
    

    or you need to initialize sammy without a selector

    var app = $.sammy(function () {
    
        this.get('#/', function (context) {
           context.log("start page");
        });
    
        this.get("#/another/:id/", function (context) {
           context.log("another page with id = " + context.params["id"]);
        });
    });
    

    it this case it attaches itself to the body element.

    Live Demo.