Durandal Routing: Mapping a route with an id?

2019-04-14 03:30发布

问题:

I have the following routes:

 router.map([                
        { url: 'home', moduleId: 'viewmodels/home', name: 'Home', visible: false },               
        { url: 'my', moduleId: 'viewmodels/folder', name: 'My Content', visible: false }, // Should display contents of /folder/2
        { url: 'public', moduleId: 'viewmodels/folder', name: 'Public Content', visible: false }, // Should display contents of /folder/3
        { url: 'set/:id', moduleId: 'viewmodels/set', name: 'Set', visible: false },
        { url: 'folder/:id', moduleId: 'viewmodels/folder', name: 'Folder', visible: false }
    ]);

I'd like to add something like this:

{ url: 'test', moduleId: 'viewmodels/folder', id: '2', name: 'Specific Folder', visible: false }

Where navigating to 'test' shows me /folder/2 (but the url stays /test). How can I achieve this using the durandal router?

回答1:

Use the settings object on the route mapping as below:

{ 
    url: 'test',
    hash: '#/test',
    moduleId: 'viewmodels/folder',
    name: 'Specific Folder',
    visible: false,
    settings: {
        id: 2
    }
}

You can debug this as in the below view model (it appears the Sammy instance is being passed in as a parameter):

define(function (require) {
    return {
        activate: activate
    };

    function activate(sammy) {
        var settings = sammy.routeInfo.settings;
        var id = settings.id;
        debugger;
    }
});

The value of id should be 2.

Hope that helps, and if it doesn't try looking a bit more at the documentation :)