Skip to content

12: CalendarCellViewをつくる

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

1. CalendarCellViewをつくる

ひとつのセルの中身が煩雑になってきたので、セルをViewクラスにします。まずはApp.CalendarCellViewをつくります。

js/view.js

//...

App.CalendarCellView = Backbone.View.extend({
  tagName: 'td',

  template:
    '<div class="calendar-date"><%= date.format("MM/DD") %></div>' +
    '<ul class="calendar-list"></ul>',

  initialize: function(options) {
    this.date = options.date;
    this.render();
  },
  render: function() {
    var html = _.template(this.template, { date: this.date });
    this.$el.html(html);

    var schedules = this.collection.findByDate(this.date);

    var $list = this.$('ul').empty();

    _.each(schedules, function(model) {
      var text = model.dateFormat('HH:mm') + ' ' + model.get('title');
      $('<li>').text(text).appendTo($list);
    });
  }
});

2. CalendarCellViewを使う

CalendarViewrender内でセルをつくっているところをCalendarCellViewに置き換えます。

js/view.js

App.CalendarView = Backbone.View.extend({
  //...
  render: function() {
    //...

    while (currentDay <= endDay) {
      var $tr = $('<tr>').appendTo($tbody);
      for (var i = 0; i < 7; i++) {
        var cell = new App.CalendarCellView({
          date: currentDay.clone(),
          collection: this.collection,
        });
        $tr.append(cell.el);
        currentDay.add(1, 'day');
      }
    }
  },
  //...
});