-
Notifications
You must be signed in to change notification settings - Fork 3
22: RouterでURLのルーティングを行う
Kazuhito Hokamura edited this page Oct 24, 2013
·
1 revision
:year/:month
のときにcalendarView.moveTo
で指定の月を描画するようにします。
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();
});
App.CalendarView = Backbone.View.extend({
//...
moveTo: function(year, month) {
this.current = moment({ year: year, month: month - 1 });
this.render();
}
});
App.router
を直接呼ばず、mediator
経由でURLを変更するようにします。
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();
});
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'));
}
});