[英]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. 与Facebook本机应用程序中的通知工具栏非常相似。 In this toolbar are 3 regions: 在此工具栏中有3个区域:
Each of these regions contains their own module (InvitesModule, RequestsModule, NotificationsModule). 这些区域中的每个区域都包含自己的模块(InvitesModule,RequestsModule,NotificationsModule)。 Each, however, has the exact same functionality: 但是,每个都具有完全相同的功能:
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? 我可以编写一个模块,例如InvitesModule,让我的另外两个模块扩展该模块,以便覆盖所需的变量吗?
Thanks and please let me know if I can be more clear 谢谢,请让我知道我能否更清楚
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. 虽然Marionette本身并不能完全允许您创建“基本模块”,但可以允许您修改现有模块。 We've taken advantage of this in our application to create a ModuleDefaults
definition that we use for all templates. 我们在应用程序中利用了这一点,创建了一个用于所有模板的ModuleDefaults
定义。 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: 使用此技术,证明第二个模块的foo
属性被覆盖:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.