Search code examples
javascriptbackbone.jsmodulemarionetteextend

How to extend a MarionetteJS module to reduce code duplication


I've got a notifications toolbar which is a module. Very similar to the notifications toolbar in the facebook native app. In this toolbar are 3 regions:

  • InvitesRegion
  • RequestsRegion
  • NotificationsRegion

Each of these regions contains their own module (InvitesModule, RequestsModule, NotificationsModule). Each, however, has the exact same functionality:

  • Check the server for new (Invites|Requests|Notifications)
  • If found, update the associated region
  • And then a whole bunch of other functions (click to popup the collectionView etc..)

Can I write a single module, say the InvitesModule and have my other two module extend that module so that I can just overwrite the variable I need to?

Thanks and please let me know if I can be more clear


Solution

  • Why yes, yes you can! While Marionette doesn't exactly allow you to create a "base module" per se, it does allow you to modify an existing module. We've taken advantage of this in our application to create a ModuleDefaults definition that we use for all templates. Here's how it works:

    var ModuleDefaults = {
      // Define baseline behavior to share among all modules
      definition: function() {
        this.foo = 'bar';
    
        this.addInitializer(function() {
          console.log(this.moduleName + ': do startup stuff');
        });
      }
    };
    

    Now you can create modules that simply implement this behavior like so:

    // Create a module with the default implementation
    App.module('Module1', ModuleDefaults.definition);
    

    Or you can create a module that overrides this bevavior:

    // Create another module with the default implementation
    App.module('Module2', ModuleDefaults.definition);
    
    // Provide customizations to second module:
    App.module('Module2', function() {
      // override existing behavior
      this.foo = 'baz';
    
      // add new behavior
      this.addFinalizer(function() {
        console.log(this.moduleName + ': cleanup stuff');
      });
    });
    

    Using this technique, prove the foo property of the second module is overridden:

    App.start();                  // -> Module1: do startup stuff
                                  // -> Module2: do startup stuff
    console.log(App.Module1.foo); // -> bar
    console.log(App.Module2.foo); // -> baz
    App.Module1.stop();           // -> 
    App.Module2.stop();           // -> Module2: cleanup stuff