Route management, the bacon.js way.
Bacon.js is a library for functional reactive programming, you can get more information about it on the github project webpage.
The idea here is to handle history states and manage client-side routing using Bacon.js.
You can install bacon-routes with bower or npm (in order to use it with browserify)
Using bower:
bower install --save bacon-routes
Using browserify, you currently have to put Bacon
in the global scope:
npm install --save bacon-routes
/* In your javascript file */
var Bacon = window.Bacon = require("baconjs");
require("bacon-routes");
Bacon.history
is a reactive property handling history changes.
Example:
Bacon.history.onValue(function(history) {
console.log(history);
});
/* Prints:
{
"state": [history forwarded from popstate],
"location": [window.location]
}
*/
Bacon.history
provides a pushState
method in order to trigger the load of a URL. See the related MDN article for further documentation.
Bacon.history.pushState(null, null, "/some-path/some-param");
Bacon.fromRoutes
is a method creating streams for each given route.
Example:
var routes = Bacon.fromRoutes({
routes: {
"users": "/users",
"user": "/users/:id"
}
});
/* Log history */
routes.users.onValue(function(history) {
console.log(history);
});
/* Log user id */
routes.user.map(function(history) {
return history.params.id;
}).log();
By default, no event is sent until the next url change. To send an event at start, use a ready
property:
var ready = new Bacon.Bus();
var routes = Bacon.fromRoutes({
ready: ready.map(true).toProperty(false),
routes: {
"users": "/users",
"user": "/users/:id"
}
});
/* Log history */
routes.users.onValue(function(history) {
console.log(history);
});
/* Log user id */
routes.user.map(function(history) {
return history.params.id;
}).log();
ready.push("Stream subscribers are ready, sir!");