EzDevInfo.com

crossroads.js

JavaScript Routes Crossroads.js: JavaScript Routes System

How to get actual value of URL in Crossroads

Lets say, I have defined a route like :

route:{
  pattern: '/root/finder/*',
  handler: finderHandler
}

If the user makes a request with url /root/finder/1234, then this matches the above pattern, and the request will be handled by finderHandler() Now, in my finderHandler, I want to get the original url value. In this case, it's /admin/finder/1234, how can i get it?


Source: (StackOverflow)

"Ignore"-URL for crossroad.js when using the A-tag with slick-binding

I'm using knockout.js and crossroad.js. (The later was configured by yeoman. I'm not sure I need it, but for now I don't know how to setup the project in another way.)

I have many a-tags with click-binding like this:

<a rel='nofollow' href='#' data-bind='click: select '>

Unfortunatelly, rel='nofollow' href='#' causes crossroars.js to change the location to home. If I remove rel='nofollow' href='#' from a-tag, the cursor over the a-tag buttons change to edit-cursor, which is not nice.

Can I use any other "dummy" value href-attribute which is ignored by crossroads.js?


Source: (StackOverflow)

Advertisements

Configure Javascript routers

For single page applications using Javascript libraries like BackboneJS/KnockoutJS as part of web application, what is the purpose of URL rewrite filters ?

Does it have anything to do with the resource layer (REST resource) ?

Also how does it differ between using query parameters (web_site/book.html?page=preface) Vs path segments (web_site/book/preface) ?

It would be great if you could explain the same in simple terms.


Source: (StackOverflow)

Refresh hasherJS/crossroadsJS routes

I’m utilizing crossroadsJS and hasherJS on an SPA powered by handlebarsJS. In retrospect I probably should have built the whole thing on Ember, but this late in it’s not wise to start over.

I have hash routes set up that switch my handlebars templates in and out based on whatever was clicked. I’m able to move backwards and forwards between the routes with no problem. However, if I refresh the page, I’m always brought back to my #/home view. I’ve done some research into window.onhashchange and window.onbeforeunload, but none of these seem to be solving the issue.

I have a very specific way of how I’m handling my views. I have a global views object constructed like so:

views.procedures = function (template) {

    this.initialize = function () {
        this.el = $('<div/>');
        this.el.attr('id', 'procedures');
        this.el.on('click', '.returned-list li a', this.toResults); // list of API objects by name
    };

    this.render = function () {
        var parts = {
            title: 'Procedures View',
        };
        this.el.html(template(parts));
        return this;
    };

    this.toResults = function () {
        cache.justClicked = $(this).attr('data-id');

        crossroads.addRoute('procedures/{name}', function () {
            api.endpoints.procedure(cache.justClicked); // constructed elsewhere
        });
    };

    this.initialize();
};

I mention this because I can’t simply add in JQuery listeners for any type of hash changes in a $(document).ready() or $(window).onhashchange

I’ve read through both the hasherJS and crossroadsJS documentations multiple times, but I’m not able to think of anything to solve the refresh issue. Thanks in advance for any help.


Source: (StackOverflow)

How can I implement links within a page, while using Client-side routing?

I'm working on an SPA, using crossroads.js for the client-side routing. Everything is working perfectly, with one exception.

I have one page within this SPA that is quite large, and I'd like to be able to use internal links, to provide a table of contents at the top. In the past, I've done something like this:

<ul>
  <li><a rel='nofollow' href="#Introduction">Introduction</a></li>
  <li><a rel='nofollow' href="#Chap1">Chapter 1</a></li>
  <li><a rel='nofollow' href="#Chap2">Chapter 2</a></li>
  <li><a rel='nofollow' href="#Chap3">Chapter 3</a></li>
</ul>

These would link to elements within the same page with the corresponding ID.

However, now that I'm using client-side routing, this doesn't seem work work as well. The page that this I'm using this on has a URL like:

http://myserver.com/#/Books/12/Full

Clicking one of the links above does move the page to the correct location on screen, but it changes the URL to:

http://myserver.com/#Chap2

Is there a standard way of handling internal links in an SPA, while preserving the URL?


Source: (StackOverflow)

Error using crossroads.js in optimized (r.js) require setup

I have developed an application using RequireJS, with no optimization layer - Require downloads each file separately. Here is the outer markup:

<!DOCTYPE html>
<html lang="en">
  <head>
     <script type="text/javascript">
       var require = {
         //some basic config
       };
     </script>
  </head>
  <body>
     <!--snip-->
  </body>
  <script type="text/javascript" data-main="main" src="scripts/lib/require.min.js"></script>
</html>

This functions without any issue, but with 100+ files the load time is really getting up there. So, time to introduce r.js optimization! I use node and r.js to create a combined file, and change data-main="main" to data-main="_build/main".

I get the following error:

Error: Mismatched anonymous define() module: (the entire body of crossroads.js)

Thoughts:

I am still digging, but hoping someone can save me some time here.


Source: (StackOverflow)

Nested Views with crossroads.js

I am trying to create a "tabbed details view" for a given entity and I need it to be deep linked with the url/hash. The hard part is I want the data to be lazy-loaded. In a perfect world, I would have a parent route at /Index.html#details/<objId> that holds all the lazy loaded data for each of its sub routes. When a user goes to /Index.html#details/<objId>/tab1 or /Index.html#details/<objId>/tab2 it can look at an object on the parent model for tab1Data or tab2Data to see if it needs to fetch data. Is there a way to do this with crossroads or maybe a better way to implement something like this?


Source: (StackOverflow)

Crossroadsjs routing: how to use it?

I am facing the same problem as this one as I am trying to figure out how to use crossroads for a few hours now and nothing seems to work. its webiste is just another poor documented site... I think I am probably daft! I wonder if anyone has made it?

html head,

<title>Crossroads</title>
  <script src="js/libs/signals.js"></script>
  <script src="js/libs/crossroads.min.js"></script>
  <script src="js/app.js"></script>
</head>

app.js, just as simple as this,

crossroads.addRoute('/news/{id}', function(id){  
  alert(id);  
}); 

so I try it out on my localhost browser,

http://localhost/crossroadjs/#/news/123

nothing happens. I thought it would be 123??


Source: (StackOverflow)

returning to root page with crossroads.js and hasher.js

I'm just starting out with crossroads.js and hasher.js and am having success parsing most of my routes. What I don't understand is how to get back to the root of the page. I know I'm not saying that right, but here's my issue:

1) I navigate to http://example.com and I see what I need to see.

2) I change the hash to http://example.com/#/foo and I do what I need to do to change the DOM.

3) I try to click back in the browser, and I'm suck here.

Maybe I need to define the "root" route in crossroads? Am I doing something wrong with the history?

Any help greatly appreciated!


Source: (StackOverflow)

How to refresh content when using CrossroadJS and HasherJS with KnockoutJS

I was following Lazy Blogger for getting started with routing in knockoutJS using crossroads and hasher and it worked correctly.
Now I needed to refresh the content using ajax for Home and Settings page every time they are clicked. So I googled but could not find some useful resources. Only these two links

  1. Stack Overflow Here I could not understand where to place the ignoreState property and tried these. But could not make it work.

        define(["jquery", "knockout", "crossroads", "hasher"], function ($, ko, crossroads, hasher) {
    
        return new Router({
            routes:
            [
                { url: '', params: { page: 'product' } },
                { url: 'log', params: { page: 'log' } }
            ]
        });
    
        function Router(config) {
            var currentRoute = this.currentRoute = ko.observable({});
    
            ko.utils.arrayForEach(config.routes, function (route) {
                crossroads.addRoute(route.url, function (requestParams) {
                    currentRoute(ko.utils.extend(requestParams, route.params));
                });
            });
            activateCrossroads();
        }
    
        function activateCrossroads() {
            function parseHash(newHash, oldHash) {
                //crossroads.ignoreState = true; First try
                crossroads.parse(newHash);
            }
            crossroads.normalizeFn = crossroads.NORM_AS_OBJECT;
    
            hasher.initialized.add(parseHash);
            hasher.changed.add(parseHash);
            hasher.init();
    
            $('a').on('click', function (e) {
                crossroads.ignoreState = true; //Second try
            });
    
        }
    });
    
  2. Crossroads Official Page Here too I could not find where this property need to be set.

If you know then please point me to some url where I can get more details about this.


Source: (StackOverflow)

using crossroads and hasher with jquery tabs navigation in spa

I am new to using crossroads.js.

I currently have a spa where one of the pages contain jquery tabs. I use hasher and crossroads to route within my spa for different pages. I have currently set prependhash to empty string so that url looks like a.com#main . In the page where i have jquery tabs if i click on one of the tabs , hasher thinks i need to navigate to a page and adds the tabs as a url like a.com#first_tab. Is there a way i can let the router know i am navigating a tab and don't want to navigate to a different page.

The code below is how my router is configured. And in the mainpage i have a jquery tabs. Clicking on the tabs calls the hasher function. and goes to a new url with a.com#first_tab instead of just navigating to the tab as expected.

my html

<nav>
    <a rel='nofollow' href="#mainpage">main </a>
    <a rel='nofollow' href="#secondpage">second page </a>
    <a rel='nofollow' href="#thirdpage">third page </a>
    <a rel='nofollow' href="#fourthpage"> fourth page </a>
</nav>
  <div id="mainpage" class='inactive-page'>
    <div id="tabs">
      <ul>
        <li><a rel='nofollow' href="#tabs-1">Nunc tincidunt</a></li>
        <li><a rel='nofollow' href="#tabs-2">Proin dolor</a></li>
        <li><a rel='nofollow' href="#tabs-3">Aenean lacinia</a></li>
      </ul>
      <div id="tabs-1">
        <p>Proin elit arcu</p>
      </div>
      <div id="tabs-2">
        <p>Morbi tincidunt</p>
      </div>
      <div id="tabs-3">
        <p>Mauris</p>
      </div>
    </div>
</div>

<div id="secondpage" class='inactive-page'>
    <h1> Second Page </h1>
</div>

<div id="thirdpage" class='inactive-page'>
    <h1> Third Page </h1>
</div>

my javascript

crossroads.addRoute('mainpage');
crossroad.addRoute('secondpage');
crossroads.addRoute('thirdpage');

function handleHashChanges(newPage, oldPage) {
    $("#"+newPage).removeClass("inactive-page");
    $("#"+oldPage).addClass('inactive-page');
}

hasher.changed.add(handleHashChanges);
hasher.initialized.add(handleHashChanges);
hasher.init();
hasher.prependHash = '';
hasher.setHash('mainpage');

Source: (StackOverflow)

Comparison of Crossroads.js and router.js

Looks like crossroads.js is much older than router.js. All the articles about crossroads.js seem to be from 2011. I'm wondering if anyone has a comparison:

  • reasons why you'd use one over the other
  • differences in how they operate
  • etc

See also: https://github.com/tildeio/router.js/issues/108


Source: (StackOverflow)

Single page application routing w/ Crossroads & Hasher, by example

I am trying to write my first single-page application. The idea is to have 1 HTML file that contains many <div> tags; where each <div> represents a single web "page". Then the application just shows 1 <div> at a time, and hides the others. In this way, as users navigate my app, I'm really just showing/hiding different "page" divs, and giving the illusion of a single page app.

Additional requirements are:

  • This is an HTML5 app
  • Each page div must map too its own bookmarkable URL (http://myapp.example.com/#fizz, http://myapp.example.com/#buzz, etc.)
  • Singe each page div is bookmarkable, the app must work with the HTML5 history api

I decided on using Crossroads for routing, and Hasher for History. The other lead contender was AngularJS, but in the end I decided against AngularJS because it was too heavyweight for what I'm trying to do here, and seemed to have a steeper learning curve associated with it.

So far, my project has the following directory structure:

myapp/
    index.html
    myapp.js
    myapp.css
    signals.min.js          <-- Required by both Crossroads and Hasher
    crossroads.min.js
    hasher.min.js

The JSFiddle containing my index.html, myapp.css and myapp.js files is here:

http://jsfiddle.net/Sxfms/2/

The idea is that the user can click one of the links in the "navbar" ("Home", "About", "Contact") and be brought to the "page" (div) representing that particular page. As you can see, the default "page" should be HOME, meaning this is the only div you should be able to see. But all the page divs are visible, and none are hidden. And until I can get the page divs showing/hiding correctly, I can't really test routing/history functionality. Have I configured Crossroads/Hasher wrong somehow?


Source: (StackOverflow)

Simultaneous external template loading and data binding with Knockout and Require

I want to send both requests for view and data, then when view and data requests responded they need to be binded. I use setInterval for this. But I don't know this is the correct way or not.

Sometimes I need to update most of ViewModel data. I can't figure out how can I update these mass data.

With this code I get both view and data. But I can't use data in viewModel. Because if I try to update data after binding I don't know what to do.

Any suggestions?

in app.js

crossroads.addRoute('/cart', function () {
    require(['cart'], function () {
        cart.init();
    });
});

in cart.js

define(['jquery', 'knockout'], function($, ko) {
    var cart = {
        viewLoaded: false,
        dataLoaded: false,
        template: '',
        cartData: {},

        container: '#container',

        // Gets external template
        getView: function () {
            $.ajax({
                ...
                success: function (response) {
                    cart.viewLoaded = true;
                    $(cart.container).html(response);
                }
            });
        },

        // Gets data
        getCart: function () {
            $.ajax({
                ...
                success: function (response) {
                    cart.dataLoaded = true;
                    cart.cartData = response;
                }
            });
        },

        ViewModel: function () {
            var self = this;

            self.cartId = ko.observable();
            self.products = ko.observableArray([]);
            .
            .
            .
        },

        // Checks both template and data are loaded
        bindings: function () {

            var loadControl = setInterval(function() {
                if (cart.viewLoaded && cart.dataLoaded) {
                    ko.applyBindings(new cart.ViewModel(), $(cart.container)[0]);
                    clearInterval(loadControl);
                }
            }, 100);
        },

        init: function () {
            this.getView();
            this.getCart();
            this.bindings();
        }
    };

    return cart;
});

Source: (StackOverflow)

Unable to load crossroads.js using RequireJS

I try to load JS files using RequireJS , however crossroads http://millermedeiros.github.io/crossroads.js/ seems not be loaded properly. I have checked using Chrome Dev Toolbar and all JS files are actually loaded. However running window.crossroad returned me undefined?

Below is my requirejs config.. Kindly advice... Thanks!

index.html

<script data-main="scripts/config" src="scripts/require.js"></script>

config.js

require.config({
  shim: {
    "zepto.min": {
      exports: "$"
    },
    "underscore.min": {
      exports: "_"
    },
    "crossroads.min": {
      exports: "crossroads"
    }  }
});

require(["zepto.min","underscore.min", "crossroads.min",], function() {
    console.log("=> Loading app")
    require(["main"]);
});

main.js

require(["hp-config", "hp-model", "hp-view", "hp-controller"], function () {
    console.log("=> Init");
    console.log(window.crossroads);
    //$(document).ready( function(){ HP.C.init(); });
});

Source: (StackOverflow)