简体   繁体   中英

PhoneGap/Cordova with client-side routing?

I've inherited a Cordova/PhoneGap app running Cordova 3.4. My first task was to implement a Client-Side Routing framework to make it easier to navigate between pages. I chose Flatiron Director as my client-side router, but when I went to implement it I started to get weird functionality out of the app.

My first router setup:

    var routing = {
        testHandler: function(){
            console.log('Route ran');
        },
        routes: function(){
            return {
                "/testhandler": testHandler
            }
        }
    };
    console.log('Routes added');

The routes are added (at least based on the console output). When I attempt to hit the /testhandler hash, I receive a "Failed to load resource: file:///testhandler" error when I set window.location.hash to "/testhandler". I noticed the "Route ran" statement was never printed.

My next attempt was just using the hashchange event with jQuery.

$(window).on('hashchange', function(){ console.log('Ran'); });

On this attempt, regardless of what I change the hash to, I see the 'Ran' output, but I still receive the "Failed to load resource: " error.

Is this a problem with PhoneGap/Cordova? Or our implementation? Is it just not possible to use client-side routing with Cordova? What am I doing wrong?

I know that this doesn't answer your question directly but you may consider making your own provisional router. This may help you to debug your app and to figure out what's the problem.

Something like this for example:

   var router = (function (routes) {
        var onRouteChange = function () {
            // removes hash from the route
            var route = location.hash.slice(1);

            if (route in routes) {
                routes[route]();
            } else {
                console.log('Route not defined');
            }
        };

        window.addEventListener('hashchange', onRouteChange, false);

        return {
            addRoute: function (hashRoute, callback) {
                routes[hashRoute] = callback;
            },
            removeRoute: function (hashRoute) {
                delete routes[hashRoute];
            }
        };
    })({
            route1: function () { 
                console.log('Route 1');
                document.getElementById('view').innerHTML = '<div><h1>Route 1</h1><p>Para 1</p><p>Para 2</p></div>';
            }, 
            route2: function () { 
                console.log('Route 2'); 
                document.getElementById('view').innerHTML = '<div><h1>Route 1</h1><p>Para 1</p><p>Para 2</p></div>';
            }
        });

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