Check alle échte Black Friday-deals Ook zo moe van nepaanbiedingen? Wij laten alleen échte deals zien

[JS] Simpele front-end router

Pagina: 1
Acties:

  • Vinze
  • Registratie: Augustus 2006
  • Laatst online: 20-11 10:29
Ik ben bezig om een eigen router te schrijven in Javascript en in principe werkt hij perfect alleen mis ik nog één ding: ik wil graag optionele parameters kunnen gebruiken.

Allereerst de code en wat voorbeeld routes:
JavaScript:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
var Router = new function() {
    // Store the routes
    var routes = [];

    // Register routes
    this.on = function(url, fn) {
        routes.push({ url: url, fn: fn });
    }

    // Run the router
    this.run = function() {
        window.addEventListener('hashchange', processRoute);
        window.addEventListener('load', processRoute);
    }

    // Start routing
    var processRoute = function () {
        // Get the hash
        var hash = location.hash.slice(1) || '/';

        // Split the hash
        var hashParts = hash.split('/').slice(1);

        // No route matched (yet..)
        var routeMatched = false;

        // Loop through the routes
        for (var x = 0; x < routes.length; x++) {

            // Split each part of the route
            var routeParts = routes[x].url.split('/').slice(1);

            // Set the routeParts/hashParts matches to zero
            var matches = 0;

            // Create the params object
            var params = {};

            // Check if the hash length matches the route length
            if (routeParts.length == hashParts.length) {

                // Loop though the hashParts
                for (var y = 0; y < hashParts.length; y++) {
                    // Check if the parts match
                    if (routeParts[y] == hashParts[y]) {
                        matches++;
                    }
                    // Check of the routePart is a parameter
                    else if (routeParts[y].substring(0, 1) == ':') {
                        params[routeParts[y].substring(1)] = hashParts[y];
                        matches++;
                    }
                    // The route matches the current hash
                    if (matches == hashParts.length) {
                        // Execute the route function
                        routes[x].fn(params);
                        routeMatched = true;
                        break;
                    }
                }
            }
        }
        if (!routeMatched) {
            console.log('Route not found....');
            // location.hash = '#/';
        }
    }
}

Router.on('/', function(params) {
    console.log('Route:', '/');
});

Router.on('/users', function(params) {
    console.log('Route:', '/users');
});

Router.on('/users/view/:id', function(params) {
    var id = params.id
    console.log('Route:', '/users/view/:id');
});


Nu heb ik het idee om een parameter uit de URL optioneel te maken door er een vraagteken achter te plaatsen:
JavaScript:
1
2
3
Router.on('/users/view/:id/:name?', function(params) { 
    ...
});


Nu had ik al een extra for loop toegevoegd welke over de routeParts heel loopt en kijkt hoeveel verplichte parameters deze bevat. Echter kreeg ik het niet voor elkaar om de juiste route te matchen, en nu krijg ik het plaatje in m'n hoofd even niet compleet hoe het wel zou moeten werken.

Iemand die me een duwtje in de juiste richting kan geven? Of eventueel tips hoe ik de code wat compacter/efficiënter kan maken?

Verwijderd

Een manier om dit sneller te doen is om dit serverside te doen.. Waarom doe je dit niet serverside, eigenlijk?

  • hillbillie
  • Registratie: November 2010
  • Laatst online: 18-07-2022
Verwijderd schreef op dinsdag 06 mei 2014 @ 06:31:
Een manier om dit sneller te doen is om dit serverside te doen.. Waarom doe je dit niet serverside, eigenlijk?
Een SPA misschien?

ontopic: waarom kijk je niet en/of gebruik je backbone?

[ Voor 22% gewijzigd door hillbillie op 06-05-2014 08:32 ]


  • Vinze
  • Registratie: Augustus 2006
  • Laatst online: 20-11 10:29
hillbillie schreef op dinsdag 06 mei 2014 @ 08:28:
[...]


Een SPA misschien?

ontopic: waarom kijk je niet en/of gebruik je backbone?
Klopt, voor wat grotere projecten gebruik ik Angular of Backbone, maar dat is in dit geval overkill. Daarnaast vind ik het ook wel leuk en leerzaam om te doen.

  • Woy
  • Registratie: April 2000
  • Niet online

Woy

Moderator Devschuur®
Dit is puur front-end en hoort dus in WEB

PRG -> WEB

“Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.”