In this article we will learn about Regular Expression Routing. If you want to be more selective in your routing and the route URL that matches the specified criteria then we can use a regular expression. Using it, the routers are converted into a regular expression object. There is only the "Router.route" method support for adding this types of route at a time.
In this tutorial we create a list of electronic and non-electronic devices and create a regular expression for both electronic devices and non-electronic devices. Here we create the regular expression for an electronic device in which we define that all electronic devices starting with the "M" character.
Now let's see how to create this application.
<!doctype html>
<html>
<head>
<title>Devices</title>
</head>
<body>
<p><a href="#/which-type-device">Device Instructions</a></p>
<h3>Types of Device</h3>
<ul class="device">
</ul>
<hr>
<script src="js/jquery.min.js"></script>
<script src="js/underscore.min.js"></script>
<script src="js/backbone.min.js"></script>
<script src="device.js"></script>
</body>
</html>
//Create Model
var Device= Backbone.Model.extend();
//Create View
var DeviceView = Backbone.View.extend({
tagName: 'li',
template: _.template('<a href="#device/<%= name.toLowerCase() %>"><%= name %></a>'),
render: function () {
this.$el.append(this.template(this.model.toJSON()));
return this;
}
});
var DeviceRouter = Backbone.Router.extend({
routes: {},
electronicDevice: function (name) {
alert('It is an electronic device ' + name + '!');
},
nonelectronicDevice: function (name) {
alert('That ' + name + ' is not a electronic device');
},
deviceWhichType: function () {
alert('Choose a device\n\n(hint:theelectronic device start with\'m\')');
},
initialize: function () {
var router = this,
routes = [
[/^device\/([a-z]+)$/, 'getNonElectronicDevice', this.nonelectronicDevice],
[/^device\/(m[a-z]+)$/, 'getElectronicDevice', this.electronicDevice],
['which-type-device', 'getAllDevice', this.deviceWhichType]
];
_.each(routes, function (route) {
router.route.apply(router, route);
});
}
});
_.each(['MobilePhone', 'Cycle', 'Monitor', 'Car', 'MicroWave', 'Chair'], function (device) {
var model = new Device({ name: device }),
view = new DeviceView({
model: model
});
view.render().$el.appendTo('.device');
});
new DeviceRouter();
Backbone.history.start();
There are various links; click on the link.