Skip to content

22: RouterでURLのルーティングを行う

Kazuhito Hokamura edited this page Oct 24, 2013 · 1 revision

1. calendarのルーティングを作成

:year/:monthのときにcalendarView.moveToで指定の月を描画するようにします。

js/app.js

window.App = {};
App.mediator = _.extend({}, Backbone.Events);

$(function() {
  var Router = Backbone.Router.extend({
    routes: {
      ':year/:month': 'calendar',
      '*default': 'today'
    },
    initialize: function() {
      //...
    },
    calendar: function(year, month) {
      this.calendarView.moveTo(year, month);
    },
    today: function() {
      this.calendarView.toToday();
    }
  });

  App.router = new Router();
  Backbone.history.start();
});

js/model.js

App.CalendarView = Backbone.View.extend({
  //...
  moveTo: function(year, month) {
    this.current = moment({ year: year, month: month - 1 });
    this.render();
  }
});

2. mediator経由でルーティングする

App.routerを直接呼ばず、mediator経由でURLを変更するようにします。

js/app.js

window.App = {};

App.mediator = _.extend({}, Backbone.Events);

$(function() {
  var Router = Backbone.Router.extend({
    routes: {
      ':year/:month': 'calendar',
      '*default': 'today'
    },
    initialize: function() {
      //...

      this.listenTo(App.mediator, 'route:change', this.changeRoute);
    },
    changeRoute: function(route) {
      this.navigate(route);
    },
    calendar: function(year, month) {
      this.calendarView.moveTo(year, month);
    },
    today: function() {
      this.calendarView.toToday();
    }
  });

  new Router();
  Backbone.history.start();
});

js/view.js

App.CalendarView = Backbone.View.extend({
  //...
  moveTo: function(year, month) {
    this.current = moment({ year: year, month: month - 1 });
    this.render();
    this.routeToCurrent();
  },
  toPrev: function() {
    this.current.subtract(1, 'month');
    this.render();
    this.routeToCurrent();
  },
  toNext: function() {
    this.current.add(1, 'month');
    this.render();
    this.routeToCurrent();
  },
  toToday: function() {
    this.current = moment();
    this.render();
    App.mediator.trigger('route:change');
  },
  routeToCurrent: function() {
    App.mediator.trigger('route:change', this.current.format('YYYY/MM'));
  }
});