简体   繁体   中英

How to use crossroads JS?

I am trying to figure out how to work with crossroads JS and kind of confused if I am on the right track.

<!DOCTYPE html>
<html>
<head>
    <title>Testing Cross Roads</title>
</head>
<body>
    <a href="#foo">Testing link</a>

    <script type="text/javascript" src="bower_components/jquery/dist/jquery.min.js"></script>
    <script type="text/javascript" src="bower_components/js-signals/dist/signals.min.js"></script>
    <script type="text/javascript" src="bower_components/crossroads/dist/crossroads.min.js"></script>

    <script type="text/javascript">
        var route1 = crossroads.addRoute('/foo', function(){
            console.log("Hello");
        });
    </script>
</body>
</html>

When I try to navigate to /#foo , I don't see any output in the console. Is this how it is supposed to work? I even created a JSFiddle .

You have two problems in that snippet.

First, you are defining the route as /foo but in the anchor tag, you are calling #foo which is totally different.

Second, crossroads doesn't handle the calling of signals on its own. You have to call crossroads.parse('/foo') in the onclick or on some other event to navigate to it. using an anchor tag like this directly won't work. You need to override the default behavior of anchor and call parse on the route.

Something like:

var overrideDefaultAction = function (e) {
    e.preventDefault();
    crossroads.parse('/' + this.href.split('/').pop());
}

var a = document.querySelectorAll('a')
for(i=0;i<a.length;i++){
    a[i].onclick = overrideDefaultAction;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM