Open nsisodiya opened 9 years ago
+1
@nsisodiya @ishuah I was able to add new routes after replacing
page('*', function () {}) //needed this to prevent default "404" redirects
page()
with this
page('*', function (ctx, next) {
ctx.handled = true
next()
})
page()
in my code
For everyone in the future, since page.js ceased to be developed i managed to extend this library by adding 2 new functions.
These functions let you add dynamically new routes. and also .exit routes.
page.addRoute = function(path, fn) {
var route = new page.Route(/** @type {string} */ (path));
for (var i = 1; i < arguments.length; ++i) {
page.callbacks.splice(1,0,route.middleware(arguments[i]));
}
};
and for exit:
page.addRoute.exit = function(path, fn) {
var route = new page.Route(path);
for (var i = 1; i < arguments.length; ++i) {
page.exits.splice(1,0,route.middleware(arguments[i]));
}
};
I also made functions to dynamically remove routes and .exit routes. If is someone interested then ask. It is a little bit harder but i can provide whole code
These functions works well inside page.js file or outside. It doesn't really matter where you define them.
Then you can simply in your program run
page.addRoute("/addRoute", function() { console.log("callback on enter") })
and
page.addRoute.exit("/addRoute", function() { console.log("callback on exit") })
As you can see, i just used splice instead of push method. So this was no big deal and for my big app with more than 30 routes it works perfectly
Hope this helps you all , who want to add another routes but still preserve *
route.
I am unable to see any example on dynamic routing with page.js Consider, an App which has navigation bar which 10 link, each link will load a new module. Let imagine we want to have a nested route. a module can have some tabs. Now when this module get loaded, only after that I want to register my route callback.
It is possible to add new routes dynamically ? Again, when the module is unloaded, I want to unregister the callback, because when I will return to that module, there will be multiple callback registered for the same route.
How to handle all these situations with page.js.
Currently I have only one solution in my mind, I will create a global eventBus at toplevel (pub/sub pattern). all the routes will be registered on top level (that is outside of all module). whenever there is route change happens, that event will be published on routeChangeEvent. modules can subscribe/unsubscribe routeChangeEvent. This way I can handle dynamic routes in my applications.