Skip to content

21: Routerを作成する

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

1. Routerを定義する

Routerを定義し、初期化をRouterのinitializeで行う。

js/app.js

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

$(function() {
  var Router = Backbone.Router.extend({
    routes: {
      '*default': 'today'
    },
    initialize: function() {
      this.schedules = new App.Schedules();
      this.schedules.fetch();

      this.calendarView = new App.CalendarView({
        el: '.calendar',
        collection: this.schedules
      });

      this.formDialogView = new App.FormDialogView({
        el: '.dialog',
        collection: this.schedules
      });

      this.calendarControlView = new App.CalendarControlView({
        el: '.calendar-control'
      });
    },
    today: function() {
      this.calendarView.toToday();
    }
  });

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

2. CalendarViewのinitializeを変更

CalendarViewinitializeのときのrenderはRouter側でおこなうようにするので削除しておく。

js/view.js

App.CalendarView = Backbone.View.extend({
  initialize: function() {
    this.listenTo(this.collection, 'add change', this.render);
    this.listenTo(App.mediator, 'calendar:prev', this.toPrev);
    this.listenTo(App.mediator, 'calendar:next', this.toNext);
    this.listenTo(App.mediator, 'calendar:today', this.toToday);
  },
  //...
});

3. 戻る、進むを押したときにURLが変わるようにする

js/view.js

App.CalendarView = Backbone.View.extend({
  //...
  toPrev: function() {
    this.current.subtract(1, 'month');
    this.render();
    App.router.navigate(this.current.format('YYYY/MM'));
  },
  toNext: function() {
    this.current.add(1, 'month');
    this.render();
    App.router.navigate(this.current.format('YYYY/MM'));
  },
  toToday: function() {
    this.current = moment();
    this.render();
    App.router.navigate('');
  }
});