Routing using jQuery router (part 1)
JQuery router is a router plugin for jQuery application. It follows custom event emitter pattern similar to jQuery events. Welcome to the first part of three part series. In this part we will learn about jQuery router and how we can use it in our production applications.
Install jQuery router
jQuery router can be installed with a simple npm install
command.
Note: You would need jQuery
and deparam.js
for the library to be functional.
npm install --save jqueryrouter@2.2.8 jquery deparam.js
Using jQuery router?
JQuery router can be added using a script tag or with bundlers like webpack and rollup:
import $ from 'jquery';
import 'jqueryrouter';$.route(...);
As a script:
<script src=".../jquery.js"></script>
<script src=".../jquery.router.min.js"></script>
<script>
$.route(...);
<script>
Writing first jQuery router application
JQuery router works like custom events.
First you attach a listener function:
import { route } from 'jqueryrouter';
route('/path/to/route', function () {
...
});
Then trigger that function by emitting a route change:
import { router } from 'jqueryrouter';
router.set('/path/to/route');
To unbind a listener you can use unroute
.
import { unroute } from 'jqueryrouter';
unroute('/path/to/route');
To attach a global listener you can use generic route:
route('*', function () {
...
});// OR simplyroute(function () {
...
});
Generic routes are favorable for production code (for many reasons). To understand why, let’s understand with the help of an example.
What would you prefer?
Approach 1:
route('/path/to/route1', handler1);
route('/path/to/route2', handler2);
route('/path/to/route3', handler3);
.
.
.
route('/path/to/route99', handler99);
Approach 2 (Generic route approach):
route(handler);function handler(e) {
switch(e.route) {
case '/path/to/route1': { ... }
case '/path/to/route2': { ... }
.
.
.
case '/path/to/route99': { ... }
}
}// OR a regular expression matchfunction handler(e) {
const match = e.route.match(/\/path\/to\/route([0-9]+)/);
switch(match[1]) { ... }
}
Generic routes are far more customizable and performant compared to simple routes. However, in real world applications you might need a combination of both.
In next tutorial we’ll build a small application with tabs to demonstrate how this works (checkout this demo).