Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhancement: Support for Both Singleton and New Instances in CustomJS Plugin #77

Closed
PxaMMaxP opened this issue Dec 26, 2023 · 0 comments · Fixed by #78
Closed

Enhancement: Support for Both Singleton and New Instances in CustomJS Plugin #77

PxaMMaxP opened this issue Dec 26, 2023 · 0 comments · Fixed by #78

Comments

@PxaMMaxP
Copy link
Contributor

Description

Currently, the CustomJS plugin loads each class as a singleton by creating an instance and storing it in the window.customJS object. This approach is efficient for shared states but limits the flexibility when multiple instances of the same class are needed in different contexts.

Suggested Enhancement

To increase the flexibility of the CustomJS plugin, I suggest modifying the evalFile method to store the class constructor instead of the instance. This change will allow users to either use a singleton instance (default behavior) or create new instances when required.

Proposed Code Changes

  async evalFile(f: string): Promise<void> {
    try {
      const file = await this.app.vault.adapter.read(f);
      const def = debuggableEval(`(${file})`, f) as new () => unknown;

      // Store the existing instance
      const cls = new def();
      window.customJS[cls.constructor.name] = cls;

      // Provide a way to create a new instance
      window.customJS[`create${def.name}Instance`] = () => new def();
    } catch (e) {
      console.error(`CustomJS couldn\'t import ${f}`)
      console.error(e)
    }
  }

Usage

For the Singleton Instance (default):

const { ClassName } = customJS;

For a New Instance (when needed):

const ClassName = customJS.createClassNameInstance();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant