Step 6 - Add Controller
-
Create file
controller.js
and add inindex.html
-
Move all router's handlers from app initialization to controller
ContactManager.Controller = Marionette.Controller.extend({ initialize: function(options) { this._contacts = options.contacts; this._router = options.router; this._mainRegion = options.mainRegion; }, home: function() { this._router.navigate('contacts', { trigger: true, replace: true }); }, showContacts: function() { var contactsView = new ContactManager.Views.Contacts({ collection: this._contacts }); ContactManager.mainRegion.show(contactsView); }, newContact: function() { var newContactForm = new ContactManager.Views.ContactForm({ model: new ContactManager.Models.Contact() }); this.listenTo(newContactForm, 'form:submitted', function(attrs) { attrs.id = this._contacts.isEmpty() ? 1 : (_.max(this._contacts.pluck('id')) + 1); this._contacts.add(attrs); this._router.navigate('contacts', true); }); ContactManager.mainRegion.show(newContactForm); }, editContact: function(id) { var contact = this._contacts.get(id), editContactForm; if (contact) { editContactForm = new ContactManager.Views.ContactForm({ model: contact }); this.listenTo(editContactForm, 'form:submitted', function(attrs) { contact.set(attrs); this._router.navigate('contacts', true); }); ContactManager.mainRegion.show(editContactForm); } else { this._router.navigate('contacts', true); } } });
-
Crate controller on application initialization and bind to router
ContactManager.addInitializer(function(data) { var contacts = new ContactManager.Collections.Contacts(data.contacts), router = new ContactManager.Router(), controller = new ContactManager.Controller({ contacts: contacts, router: router, mainRegion: this.mainRegion }); router.on('route:home', controller.home, controller); router.on('route:showContacts', controller.showContacts, controller); router.on('route:newContact', controller.newContact, controller); router.on('route:editContact', controller.editContact, controller); });