How to add a refresh method to a backbone router

While creating a simple web app, where I created an ajax powered form using backbone.js, I needed the ability to clear the form if the user hit the reset button. So, I thought how about if I just refresh the current view. Backbone.js does not have a method to do that, which is a bit counter intuitive. After searching and trying a few things, the best answer was found in the comments of this blog post. Thanks to user mpeg for the contribution. The solution is simply to add the following extension method to the router prototype anywhere before you call the refresh method. Since Javascript is a prototypal inheritance language, this gets added dynamically to the existing instances of the router.

_.extend(Backbone.Router.prototype, {
      refresh: function () { var tmp = Backbone.history.fragment; this.navigate(tmp + (new Date).getTime()); this.navigate(tmp, { trigger: true }); }

I would just put it right where I am creating the AppRouter.

Leave a comment

Your email address will not be published. Required fields are marked *