How to extend a MarionetteJS module to reduce code duplication

十年热恋 提交于 2019-12-11 12:29:45

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/18500984/how-to-extend-a-marionettejs-module-to-reduce-code-duplication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!