Override method of an existing instance

135 views Asked by At

I'm trying to extend an existing Durandal router plugin instance already created with the help of RequireJS.

The method map() should be overriden to add extra mapping parameters.

How should I access the original method from the modified one?

index.js

define([ 'durandal/app', 'app/childRouter'], function(
        app, childRouter) {
    childRouter.map([ {
        route : 'details/:id',
        moduleId : 'details/index',
    }, {
        route : 'details/tabs/base',
        moduleId : 'details/tabs/base',
    } ]);
    childRouter.buildNavigationModel();

    return {
        router : childRouter
    };
});

childRouter.js

define([ 'durandal/app', 'plugins/router'], function(
        app, router) {

    var childRouter = router.createChildRouter();
    childRouter._map = childRouter.map;
    childRouter.map = function(data) {
        data.unshift({
            route : [ '', 'grid' ],
            moduleId : 'grid/index',
        });
        childRouter._map(data);//CALLS THE OVERRIDEN METHOD AGAIN INSTEAD OF ORIGINAL
    };
    return childRouter;
});
1

There are 1 answers

3
jestermax On

If you want to still call the original "map" function, you'll need to store it before you overwrite it. It's a bit "hacky" to replace functions in this way, but if you REALLY had to do it, this will work:

var childRouter = router.createChildRouter();
childRouter.originalMap = childRouter.map;  // Save original
    childRouter.map = function(data) {
        data.unshift({
            route : [ '', 'grid' ],
            moduleId : 'grid/index',
        });
        childRouter.originalMap(data);    // Call original
    };