Quantcast
Viewing latest article 1
Browse Latest Browse All 15

Using modifyClass for objects which are initialized early in boot

When using modifyClass in an initializer, you may see this warning in the console:

(type) has already been initialized and registered as a singleton. Move the modifyClass call earlier in the boot process (e.g. to a pre-initializer) for changes to take effect.

(Prior to April 2023, the error text “(type) was already cached in the container. Changes won’t be applied.”)

This commonly happens when overriding methods on services (e.g. topicTrackingState), and on models which are initialized early in the app boot process (e.g. a model:user is initialized for service:current-user).

To resolve this warning, you need to move the modifyClass call earlier in the boot process. In a theme/plugin, that normally means moving the call to a pre-initializer, and configuring it to run before Discourse’s ‘inject-discourse-objects’ initializer. For example:

// (plugin)/assets/javascripts/discourse/pre-initializers/extend-user-for-my-plugin.js
// or
// (theme)/javascripts/discourse/pre-initializers/extend-user-for-my-plugin.js

import { withPluginApi } from "discourse/lib/plugin-api";

export default {
  name: "extend-user-for-my-plugin",
  before: "inject-discourse-objects",

  initializeWithApi(api){
    api.modifyClass("model:user", {
      myNewUserFunction() {
        return "hello world";
      }
    });
  },

  initialize() {
    withPluginApi("0.12.1", this.initializeWithApi);
  },
};

This modification of the user model should now work without printing a warning, and the new method will be available on the currentUser object.

Read full topic


Viewing latest article 1
Browse Latest Browse All 15

Trending Articles