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
... 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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With