Skip to content

Code Standards

Jorch C. edited this page Nov 26, 2024 · 1 revision

Here’s a set of JavaScript Standards and Guidelines tailored for your Webtricks project to maintain consistency and quality across all scripts:


JavaScript Standards for Webtricks

General Standards

  1. Use Strict Mode:

    • Always start your scripts with 'use strict'; to enforce better coding practices and catch common errors early.
    'use strict';
  2. Class-Based Structure:

    • Each functionality should be encapsulated in a class with clear and descriptive naming.
    • Class names should use PascalCase (e.g., CMSFilter, FormCheck).
  3. Self-Initializing on Page Load:

    • All scripts should initialize automatically when the DOM is fully loaded.
    • Use the following pattern for initialization:
      const InitializeFunctionality = () => {
          window.trickeries = window.trickeries || [];
          const elements = document.querySelectorAll('[wt-attribute]');
          elements.forEach(element => {
              const instance = new FunctionalityClass(element);
              window.trickeries.push({ 'FunctionalityClass': instance });
          });
      };
      
      if (/complete|interactive|loaded/.test(document.readyState)) {
          InitializeFunctionality();
      } else {
          window.addEventListener('DOMContentLoaded', InitializeFunctionality);
      }
  4. Add to window.webtricks Object:

    • Every script should register its instance on the window.trickeries (or window.webtricks) object.
    • This makes all functionality accessible globally for debugging or custom interactions:
      window.trickeries.push({ 'ScriptName': instance });
  5. HTML Attribute-Based Configuration:

    • Use HTML data attributes (e.g., wt-scriptname-attribute) for configuration, ensuring non-developers can easily use the scripts.
    • Provide default values for attributes if they are not explicitly set.
  6. Error Handling:

    • Include try...catch blocks to gracefully handle errors during initialization and runtime.
    • Log errors to the console with clear and descriptive messages:
      try {
          // Initialization logic
      } catch (err) {
          console.error(`Error initializing ScriptName: ${err.message}`);
      }

Standards for New Functionalities

Initialization

  • Use a constructor to initialize the script, accepting a container or relevant DOM element as a parameter.
  • Validate required attributes and elements in the constructor, and throw an error if essential data is missing.

HTML Attribute Standards

  • Use the wt- prefix for all attributes to avoid conflicts with other libraries.
  • Use descriptive names:
    • Primary functionality: wt-scriptname-element
    • Configuration options: wt-scriptname-option

Automatic Initialization

  • The script must automatically initialize by targeting elements with wt- attributes. For example:
    const InitializeScript = () => {
        const elements = document.querySelectorAll('[wt-scriptname-element="target"]');
        elements.forEach(element => new ScriptName(element));
    };

Global Registration

  • Register all instances on window.trickeries:
    const instance = new ScriptName(element);
    window.trickeries.push({ 'ScriptName': instance });

Error Messages

  • Errors must provide context to help users identify issues:
    throw new Error("ScriptName: Required attribute 'wt-scriptname-option' is missing.");

Code Quality

  1. Use Modern ES6+ Syntax:

    • Use const and let instead of var.
    • Use arrow functions for callbacks and shorter methods where appropriate:
      element.addEventListener('click', () => {
          // Callback logic
      });
  2. Avoid Hardcoding Values:

    • Use attributes or defaults for all configurable values.
  3. Keep Scripts Lightweight:

    • Avoid dependencies like jQuery unless absolutely necessary.
    • Ensure functionality is modular and reusable.
  4. Avoid Polluting the Global Namespace:

    • Keep all logic encapsulated in the class or inside closures.

Documentation Standards

  • Every script must include the following in comments:
    • Description: What the script does.
    • Required Attributes: List of HTML attributes needed for the script to work.
    • Optional Attributes: List of attributes with their default values.
    • Usage Example: HTML snippet demonstrating usage.
    • Initialization Logic: How the script initializes on page load.

Example:

/**
 * ScriptName - Brief description of what the script does.
 *
 * Required Attributes:
 * - `wt-scriptname-element`: Defines the element to be targeted by this script.
 *
 * Optional Attributes:
 * - `wt-scriptname-option`: Customizes the script behavior (default: 10).
 *
 * Usage:
 * <div wt-scriptname-element="example" wt-scriptname-option="20"></div>
 *
 * Automatically initializes on DOMContentLoaded.
 */

Consistency

  • All scripts must:
    • Follow the same initialization logic.
    • Use the same error-handling structure.
    • Provide clear and consistent logging messages.