Security News
tea.xyz Spam Plagues npm and RubyGems Package Registries
Tea.xyz, a crypto project aimed at rewarding open source contributions, is once again facing backlash due to an influx of spam packages flooding public package registries.
@nekr/navigo
Advanced tools
Readme
A simple minimalistic JavaScript router with a fallback for older browsers.
Via npm with npm install navigo
or drop lib/navigo.min.js
into your page.
var root = null;
var useHash = true; // Defaults to: false
var hash = '#!'; // Defaults to: '#'
var router = new Navigo(root, useHash, hash);
The constructor of the library accepts three argument - root
, useHash
and hash
. The first one is the main URL of
your application. If you call the constructor without parameters then Navigo figures out the root URL based on your routes.
If useHash
set to true
then the router uses an old routing approach with hash in the URL. Navigo anyways falls back
to this mode if there is no History API supported. The hash
parameter allows you to configure the hash character. To
make your URLs crawlable by Google you should use use '#!'. Read more at developers.google.com.
router
.on('/products/list', function () {
// display all the products
})
.resolve();
router
.on(function () {
// show home page here
})
.resolve();
router
.on({
'/products/list': function () { ... },
'/products': function () { ... },
...
})
.resolve();
The order of routes adding do matter. The URL which is added earlier and matches wins. For example:
router
.on({
'products/:id': function () {
setContent('Products');
},
'products': function () {
setContent('About');
},
'*': function () {
setContent('Home')
}
})
.resolve();
on
multiple times we should consider the order of the calls.router
.on('/user/:id/:action', function (params) {
// If we have http://site.com/user/42/save as a url then
// params.id = 42
// params.action = save
})
.resolve();
Every handler receives the GET parameters passed to the page.
router
.on('/user/:id/:action', function (params, query) {
// If we have http://site.com/user/42/save?answer=42 as a url then
// params.id = 42
// params.action = save
// query = answer=42
})
.resolve();
In the case of the default handler and notFound
handler the function receives only query
as parameter. For example:
router.notFound(function (query) {
// ...
});
router
.on(/users\/(\d+)\/(\w+)\/?/, function (id, action) {
// If we have http://site.com/user/42/save as a url then
// id = 42
// action = save
})
.resolve();
Wild card is also supported:
router
.on('/user/*', function () {
// This function will be called on every
// URL that starts with /user
})
.resolve();
Have in mind that every call of on
do not trigger a route check (anymore). You have to run resolve
method manually to get the routing works.
router.notFound(function () {
// called when there is path specified but
// there is no route matching
});
Use the navigate
method:
router.navigate('/products/list');
You may also specify an absolute path. For example:
router.navigate('http://site.com/products/list', true);
If you want to bind page links to Navigo you have to add data-navigo
attribute. For example:
<a href="about" data-navigo>About</a>
(Have in mind that you have to fire updatePageLinks
every time when new links are placed on the page so Navigo does the binding for them.)
It's translated to:
// the html to: <a href="javascript:void(0);" data-navigo>About</a>
var location = link.getAttribute('href');
...
link.addEventListener('click', e => {
e.preventDefault();
router.navigate(location);
});
Use the following API to give a name to your route and later generate URLs:
router = new Navigo('http://site.com/', true);
router.on({
'/trip/:tripId/edit': { as: 'trip.edit', uses: handler },
'/trip/save': { as: 'trip.save', uses: handler },
'/trip/:action/:tripId': { as: 'trip.action', uses: handler }
});
console.log(router.generate('trip.edit', { tripId: 42 })); // --> /trip/42/edit
console.log(router.generate('trip.action', { tripId: 42, action: 'save' })); // --> /trip/save/42
console.log(router.generate('trip.save')); // --> /trip/save
The resolving of the routes happen when resolve
method is fired which happen:
router.resolve()
navigate
Sometimes you need to update the URL but you don't want to resolve your callbacks. In such cases you may call .pause()
and do .navigate('new/url/here')
. For example:
r.pause();
r.navigate('/en/products');
r.resume(); // or .pause(false)
The route will be changed to /en/products
but if you have a handler for that path will not be executed.
There is an API that allows you to run functions before firing a route handler. The hooks
object is in the format of:
{
before: function (done) { ... done(); },
after: function () { ... }
}
You may specify only one (or both) hooks. The before
hook accepts a function which you must invoke once you finish your job. Here is an examples:
router.on(
'/user/edit',
function () {
// show user edit page
},
{
before: function (done) {
// doing some async operation
done();
},
after: function () {
console.log('Data saved.');
}
}
);
You may prevent the handler to be resolved in the before
hook by invoking done(false)
:
router.on(
'/user/edit',
function () {
// show user edit page
},
{
before: function (done) {
if(!user.loggedIn) {
done(false);
} else {
done()
}
}
}
);
You may provide hooks in two other cases:
router.on(function() { ... }, hooks)
router.notFound(function() { ... }, hooks)
router.on(function)
- adding handler for root/main routerouter.on(string, function)
- adding a new routerouter.on(object)
- adding a new routerouter.off(handler)
- removes the routes associated with the given handler/functionrouter.navigate(path='', absolute=false)
- if absolute
is false
then Navigo finds the root path of your app based on the provided routes.router.resolve(currentURL=undefined)
- if currentURL
is provided then the method tries resolving the registered routes to that URL and not window.location.href
.router.destroy
- removes all the registered routes and stops the URL change listening.router.link(path)
- it returns a full url of the given path
router.pause(boolean)
- it gives you a chance to change the route without resolving. Make sure that you call router.pause(false)
so you return to the previous working state.router.disableIfAPINotAvailable()
- well, it disables the route if History API is not supportedrouter.updatePageLinks()
- it triggers the data-navigo
links binding processrouter.notFound(function)
- adding a handler for not-found URL (404 page)router.lastRouteResolved()
- returns an object with the format of { url: <string>, query: <string> }
matching the latest resolved routeThere are couple of static properties. You'll probably never need to touch them but here're they:
Navigo.PARAMETER_REGEXP = /([:*])(\w+)/g;
Navigo.WILDCARD_REGEXP = /\*/g;
Navigo.REPLACE_VARIABLE_REGEXP = '([^\/]+)';
Navigo.REPLACE_WILDCARD = '(?:.*)';
Navigo.FOLLOWED_BY_SLASH_REGEXP = '(?:\/$|$)';
Navigo.MATCH_REGEXP_FLAGS = '';
Navigo.MATCH_REGEXP_FLAGS
could be useful when you want a case insensitive route matching. Simple use Navigo.MATCH_REGEXP_FLAGS = 'i'
.
npm i
npm test
// or npm run test-chrome
// or npm run test-firefox
FAQs
A simple vanilla JavaScript router with a fallback for older browsers
The npm package @nekr/navigo receives a total of 0 weekly downloads. As such, @nekr/navigo popularity was classified as not popular.
We found that @nekr/navigo demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Tea.xyz, a crypto project aimed at rewarding open source contributions, is once again facing backlash due to an influx of spam packages flooding public package registries.
Security News
As cyber threats become more autonomous, AI-powered defenses are crucial for businesses to stay ahead of attackers who can exploit software vulnerabilities at scale.
Security News
UnitedHealth Group disclosed that the ransomware attack on Change Healthcare compromised protected health information for millions in the U.S., with estimated costs to the company expected to reach $1 billion.