Skip to content

Step 6 - Add Controller

Compare
Choose a tag to compare
@dmytroyarmak dmytroyarmak released this 05 Feb 10:48
· 3 commits to gh-pages since this release
  1. Create file controller.js and add in index.html

  2. 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);
        }
      }
    });
    
    
  3. 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);
    });
    

Difference