Sammy routing not working

◇◆丶佛笑我妖孽 提交于 2019-12-23 11:00:41

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/16040732/sammy-routing-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!