Search code examples
apostrophe-cms

ApostropheCMS Moog Type - Extend your own Custom Module


Extend your own Module

This question is basically a good question for a beginner who just new to OOP language. I found your code here said that extending module using afterConstruct is a good practice. Can you teach us how to EXTEND it from other module and IMPLEMENT the extended method from other module ? I followed your example when building my Own Contact Form Module here :

  afterConstruct: function(self) {
    self.setSubmitSchema();
  },

  construct: function(self, options) {

    self.setSubmitSchema = function() {
      self.submitSchema = self.apos.schemas.subset(self.schema,
        [ 'name', 'email', 'title', 'body' ]
      );
    };

Below is my point of view of using Moog Type , are those correct ?

construct -> every method ATTACHED to the construct . beforeConstruct -> Only applicable if you extending options like addFields , removeFields and alterFields to it. afterConstruct -> Applicable for EXTENDING module/method


Solution

  • This question is too general, but what you need is a good example of this being done correctly.

    For that, just look at any pieces module we've implemented, for instance look at apostrophe-redirects, which extends pieces, adding a beforeSave method override to do something custom.

    See also the apostrophe-samples project which contains several examples of pieces modules with overrides. Again, these extend apostrophe-pieces, so they demonstrate what you are asking about.

    Regarding the three functions:

    beforeConstruct is for adjusting options first before the module you're extending gets to see it. Useful when a subclass needs to add fields to addFields, for instance.

    construct is for attaching methods to self.

    And afterConstruct is for initialization, accomplished by invoking some of those methods. This is the right time because subclass modules have had a chance to override some of those methods before afterConstruct runs.