如何延长MarionetteJS模块,以减轻code复制 [英] How to extend a MarionetteJS module to reduce code duplication

查看:92
本文介绍了如何延长MarionetteJS模块,以减轻code复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通知栏是一个模块。非常类似于facebook的本机应用程序的通知栏。在此工具栏有3个区:

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

每个这些区域都包含自己的模块(InvitesModule,RequestsModule,NotificationsModule)。每次,却拥有完全相同的功能:

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


  • 检查服务器新(邀请|请求|通知)

  • 如果找到,更新相关联的区域

  • 然后一大堆的其他功能(点击弹出的CollectionView等)

我可以写一个单独的模块,说InvitesModule,并有我的另两个扩展模块该模块,这样我就可以覆盖我需要的变量?

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

推荐答案

为什么是的,是的,你可以!虽然木偶并不完全允许您创建一个基础模块本身,它允许你修改现有的模块。我们已经采取了利用这一点在我们的应用程序创建一个 ModuleDefaults 定义,我们使用的所有模板。下面是它如何工作的:

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);

或者你可以创建一个覆盖此bevavior模块:

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');
  });
});

使用这种技术,证明第二个模块的属性覆盖:

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

这篇关于如何延长MarionetteJS模块,以减轻code复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆