Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
express like middleware thing for backbone.js (again 'n again)
/**
* @module backbone.mv
* @author Eray Arslan <relfishere@gmail.com>
* @data 11.01.2017
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['backbone', 'underscore'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('backbone'), require('underscore'));
} else {
factory(window.Backbone, window._);
}
})(function (Backbone, _) {
var base = Backbone.Router.prototype.route;
_.extend(Backbone.Router.prototype, {
route: function (route, name, callback) {
var callbacks = this.use ? this.use : [];
if (_.isFunction(name)) {
callbacks = callbacks.concat(name);
name = '';
}
return base.call(
this,
route,
name,
_.bind(function () {
var req = {
params: _
.values(arguments)
.filter(function (i) {
return i;
})
};
if (_.isString(name)) {
callbacks = callbacks.concat(this[name]);
}
(function waterfall(i) {
if (callbacks.length && callbacks[i]) {
return function () {
callbacks[i]
.bind(this)(
req,
waterfall(i + 1).bind(this)
);
};
} else {
return function () {};
}
})(0).bind(this)(req);
}, this));
}
});
});
/* */
var hello = function (req, next) {
console.log('Hi!');
next();
};
/* */
var homeViewBefore = function (req, next) {
console.log('Home Before!');
next();
};
var homeView = function (req, next) {
console.log('HOME SWEET HOME <3');
};
/* */
var productListView = function (req, next) {
console.log("PRODUCT LIST VIEW :)");
};
/* */
var productItemView = function (req, next) {
console.log("PRODUCT ITEM /w", req.params[0]);
};
/* */
var _default = function (req, next) {
console.log("Not Found", req.params[0]);
};
/* */
var Router = Backbone.Router.extend({
routes: {
"": "home",
"products": "productList",
"products/:id": "productItem",
"profile/:slug": function (req, next) {
console.log("PROFILE", req.params[0]);
console.log(arguments);
},
"about": function (req, next) {
console.log("Eray Arslan :(");
console.log(arguments);
},
"events/:id": "onAction",
"*path": _default
},
use: [hello],
home: [homeViewBefore, homeView],
productList: productListView,
productItem: productItemView
});
var router = new Router();
router.on("route:onAction", function (id) {
console.log(id);
});
Backbone.history.start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment