xyhc5a
Last Updated: February 25, 2016
·
1.532K
· sydcanem
4064c3cb5b548dd398b98621a3388c3a

Simple router mixin for React

var RouterMixin = {
  respondTo: function(routes, root, pushState) {
    var self = this;

    if (!router) {
      router = new Backbone.Router();
    }

    for (var route in routes) {
      var name = 'route' + routeId++;
      router.route(route, name, routes[route].bind(self));
    }

    if (!started) {
      pushState = !!pushState;
      Backbone.history.start({ root: root || '/', pushState: pushState });
      started = true;
    }
  }
};

Example:

React.createClass({
  mixin: [Router],
  componentDidMount: function() {
    this.respondTo({
      '': this.fetchData,
      'features/:id': this.fetchFeature
    });
  },
  fetchData: function() {
    ...
  },
  fetchFeature: function(id) {
    ...
  }
});

Credits:

https://gist.github.com/darthapo/7165970

Say Thanks
Respond