What is the process of incorporating custom methods into custom constructors in javascript?

As a newcomer to javascript, I have been exploring various libraries and came across VueJS, which I find truly impressive. Take a look at this example :

HTML :

 <h1 id="test">{{ test }}, I like Javascript</h1>

JS :

 var vue = new Vue({
   el: "#test",
   data: {
      test: "Yes"
   }
 });
 return vue;

Output :

 Yes, I like javascript

The syntax structure of VueJS truly amazed me. It got me thinking, can I create something similar? But being relatively inexperienced, I find it challenging. That's why I need some help. Let's start with something very basic :

HTML :

  <h1 id="test"></h1>

JS :

  var my = new MyCustomOne({
    el: "#test",
    html: "Hello Everyone",
    css: {
      color: "white",
      backgroundColor: "#008eff"
    }
   });

I don't want to import a large library for just a few functions. Plus, I have a desire to create something of my own. Can you assist me in creating the MyCustomOne() constructor with the methods mentioned above? Thank you in advance.

Answer №1

Here is a clever solution for your problem. Take a look at this snippet of code:

 function CustomFunction(data) {
   var elements = document.querySelectorAll(data.element); // Selecting all elements that match your selector
   for( var i = 0; i < elements.length; ++i ) {
     elements[i].innerHTML += data.content; // Adding the specified content 
     elements[i].style.cssText = data.style; // Applying the specified CSS properties
     elements[i].style[data.cssProperty] = data.cssValue; // Nested CSS property and value setting
   };
 };

You can make use of it like this:

 var custom = new CustomFunction({
   element: ".example",
   content: "Hello Universe!",
   style: "background: green",
   css: {
      property: "color",
      value: "black",
   }
  });

However, I recommend getting a good grasp of JavaScript first before delving into any JavaScript libraries or frameworks like React or Angular.

Answer №2

Creating your own version of Vue can be a challenging task, especially for beginners due to its complexity. However, there are some repositories that can help you understand the implementation of Vue core:

Alternatively, if you are looking for a simpler and lighter alternative to Vue, you may want to consider trying out the Mithril (9.5kb) framework.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transforming JSON into Excel format with Azure Function and storing it in blob storage

Is there a way to store the Excel file generated by this JavaScript code in a blob storage? I'm looking for a solution similar to fs.safeFileSync. Any ideas on how to achieve this? const fs = require('fs'); var json2xls = require('json2 ...

I'm having difficulty mocking a function within the Jest NodeJS module

I have a module in NodeJS where I utilize a function called existsObject to validate the existence of a file in Google Storage. While testing my application with Jest 29.1.2, I am attempting to create a Mock to prevent the actual execution of this functio ...

Guide on how to trigger the opening of a side panel with a button click in Vue.js

Embarking on my first Vue app development journey, I find myself in need of guidance on how to trigger the opening of a panel by clicking a button within the header. Starting off with a simple HTML template, my goal is to add some interactivity upon click ...

The NextJs error message states: "`nextCallback` is not defined as a function

Having trouble setting up Redux with Next.js for the first time. I keep encountering errors no matter what approach I try, and it's becoming difficult to configure properly. It's frustrating to see so many error messages. TypeError: nextCallback ...

Retrieve the URL for the React component

I'm facing some challenges with React fundamentals :/ I have a piece of code that creates a table using JSON data: import React from 'react' import { DataTable } from 'react-data-components'; function createTable(data) { ...

Is it possible to consolidate geometry in each frame during the rendering process using three.js?

Having recently delved into three.js, I've been experimenting with some concepts. My current challenge involves creating a line in the scene and using it as a reference for cloning and transforming. The goal is to display the cloned lines in a sequent ...

delaying the alteration of an image attribute following an AJAX call

After clicking on a button, a function is triggered (think of it as a published/unpublished button). Immediately after the function is activated, I change the element to display a loader gif. function updateStatus(event, status, element, data, action) { ...

Error: The function you are trying to reference is undefined

I am facing an issue where I am receiving a "ReferenceError: doNotification is not defined" message when attempting to display a pop-up notification upon successful promise. Oddly enough, triggering doNotification on button click within my HTML works wit ...

I keep running into errors whenever I try to run npm install in my React JS project. The only way for me to successfully install dependencies is by using npm install --force. How can I go about resolving these

I am encountering this error message while working on my project: npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @mui/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="681b1c11040d1b ...

Adding additional functionalities to ng-blur within the controller: A step-by-step guide

I am seeking to enhance the functionality of ng-blur for all input and textarea fields by adding a new function. These elements already have an existing ng-blur defined in the HTML, and my goal is to incorporate a new function into this existing setup from ...

Changing time format from ISO time to short time in JavaScript

I am working on an ajax call that retrieves a time in the format 16:06:59, and I need to convert it to 4:06 PM. var mydate = obj[0].time; The variable mydate contains 16:06:59, but when I try to use it with var date = new Date(), it returns today's ...

Is there anybody who can assist me with ${}?

Having an issue with using ${'variable'+i} in a loop function. The goal is to call each function from a loop. Explored template literals but couldn't find a solution for this specific problem. Desired format: ${'variable'+i} // (w ...

Utilizing Vue 3 props validation in conjunction with the power of Typescript

Looking to customize a Link component using Nuxt, Typescript, and the composition-api. The prop target can accept specific values as outlined below. I'm curious if using a custom validator function to check prop types at runtime adds value when compar ...

encountering an issue: file or directory does not exist, unable to open 'rds-combined-ca-bundle.pem'

I recently downloaded AWS secure socket for my Node server and integrated it into my index.js folder. However, I encountered an error that reads: "Error: ENOENT: no such file or directory, open 'rds-combined-ca-bundle.pem'. Could someone help me ...

Revitalizing and rerouting page upon button click

The issue at hand is: When the "Post now" button is clicked, the modal with the filled form still appears. If the button is clicked again, it adds the same data repeatedly. I aim to have the page refresh and navigate to a link containing the prediction d ...

Showing post response (XMLHttpRequest) on Chrome extension interface instead of Python console

I am currently developing a Chrome extension that sends a post request with information about the specific URL being browsed by the user to Flask (local host). A web scraping process is then carried out on this URL to determine a category based on the obta ...

Creating multiple Vue apps under one project can be a great way to manage different sections

Recently, I started learning Vue.js and working on an e-commerce project using Firebase. While exploring Firebase, I discovered the multiple hosting features it offers which could assist me in hosting the client and admin sides on two different domains. ...

When dynamically accessed, the property of a JSON object is considered "undefined"

I'm running into trouble trying to access properties of a JSON object in my JavaScript code using obj[varWithPropName]. Strangely, it does work when I use obj["PropName"]. Here's a simplified snippet for reference: import * as CharInfo from &ap ...

Alter the style of a div by clicking on a button

Can the background image of a div be changed by selecting a button outside of the div? For example: HTML <div id="change"></div> <div id="buttons"> <button class="button1">this</button> <button class="button2"> ...

Unable to forward to another page using NodeJS (Express)

After spending a considerable amount of time trying to find a solution, I finally managed to create a simple button click redirection using NodeJS and Express. However, when clicking on the "Next page" button in my index.html file, I encountered an error s ...