Skip to content
Marcelo XP edited this page Jan 17, 2025 · 6 revisions

Basic Usage

The JsBaseClass library is designed to simplify JavaScript development by providing a robust foundation for building modular and reusable components. This page demonstrates the most basic usage of JsBaseClass, starting with a simple example and then expanding to include local class properties.


1. Minimal Example

Here’s the most basic example of using JsBaseClass. This example initializes the class and logs a message to the console.

JavaScript

class MyApp extends JsBaseClass {
    async handle() {
        // Your initialization code here
        this.console.log('Your code starts here...');
    }

    async onDomContentLoaded() {
        // On DOM content loaded (page load)
        this.console.log('DOM content loaded');
    }
}

window.myApp = new MyApp();
myApp.init();

Explanation

  • handle Method: This is the main entry point for your class. It runs as soon as the class is instantiated and init is called. Use this method for initialization code that doesn’t depend on the DOM being fully loaded.

  • onDomContentLoaded Method: This method is automatically triggered when the DOMContentLoaded event fires, meaning the DOM is fully loaded and ready for manipulation. Use this method for code that depends on the DOM, such as selecting elements or binding events.

  • this.console: The built-in logging system provides color-coded logs for better readability, making it easier to debug and track the flow of your application.

  • Initialization: The class is instantiated and initialized using window.myApp = new MyApp(); myApp.init();. This ensures that both the handle and onDomContentLoaded methods are properly set up and executed at the right time.


By separating initialization logic (handle) from DOM-dependent logic (onDomContentLoaded), you ensure that your code runs efficiently and avoids errors caused by accessing elements before they are available. 🚀


2. Local Class Properties

In this example, we expand the basic usage to include local class properties. These properties can be used to store data or state specific to the class instance.

JavaScript

class MyApp extends JsBaseClass {
    constructor() {
        super();
        // Define local properties
        this.counter = 0;
    }

    async handle() {
        // Access and modify local properties
        this.console.log(`Initial Counter: ${this.counter}`);
        this.incrementCounter();
    }

    incrementCounter() {
        this.counter += 1;
        this.console.log(`Counter incremented to: ${this.counter}`);
    }
}

// Initialize the app
window.myApp = new MyApp();
myApp.init();

Explanation

  • Local Properties: The counter property are defined in the constructor and can be accessed throughout the class.
  • Methods: The incrementCounter method demonstrate how to modify local properties.
  • Logging: The this.console object is used to log property values and track changes.

Output in Console

For the second example, the console output will look like this:

Initial Counter: 0
Counter incremented to: 1

Why Use Local Properties?

  • Encapsulation: Local properties keep your data and logic contained within the class, promoting clean and modular code.
  • Reusability: Methods that operate on local properties can be reused across different parts of your application.
  • State Management: Local properties are ideal for managing state within a class instance.

3. Example with Instance Variables

In this example, we demonstrate how to pass an instance variable (e.g., an API key) when creating a new instance of the class. This allows you to initialize the class with specific data or configurations.

JavaScript

class MyApp extends JsBaseClass {
    constructor(apiKey) {
        super();
        // Store the API key as a local property
        this.apiKey = apiKey;
    }

    async handle() {
        // Use the API key in your initialization logic
        this.console.log(`API Key: ${this.apiKey}`);

        // Example: Make an API request using the key
        await this.fetchData();
    }

    async fetchData() {
        try {
            this.console.info('Fetching data...');
            const response = await axios.get('https://api.example.com/data', {
                headers: {
                    Authorization: `Bearer ${this.apiKey}`, // Use the API key in the request
                },
            });
            this.console.log('Data fetched:', response.data);
        } catch (error) {
            this.console.error('Error fetching data:', error);
        }
    }
}

// Initialize the app with an API key
window.myApp = new MyApp('your_api_key_here');
myApp.init();

Explanation

  • Instance Variable (apiKey): The apiKey is passed to the constructor when the class is instantiated. This allows you to configure the class with specific data (e.g., an API key) at runtime.
  • Usage in Methods: The apiKey is stored as a local property (this.apiKey) and can be used throughout the class, such as in the fetchData method to authenticate API requests.
  • Initialization: The class is instantiated with window.myApp = new MyApp('your_api_key_here');, passing the API key as an argument.

Output in Console

For this example, the console output will look like this:

API Key: your_api_key_here
Fetching data...
Data fetched: { ... }

Why Use Instance Variables?

  • Flexibility: Instance variables allow you to configure the class with specific data or settings when it’s created.
  • Encapsulation: By passing data through the constructor, you keep the class self-contained and avoid relying on global variables.
  • Reusability: The same class can be reused with different configurations by passing different values to the constructor.

Start building smarter and more efficient JavaScript applications with JsBaseClass! 🚀

Clone this wiki locally