Why does different declaration way of a class cause different interpretion of “this”

guys:

I am new to javascript. I have a question about the keyword this. I had expected both draws1 and drawc1 show window in the browser’s developer tool. but calling draws1 only returns undfined. I wonder why different declartion way cuses the difference. This is my code:

class Square {
 constructor(x, y, size) {
    this.x = x;
    this.y = y;
    this.size = size;
 }

//instance method
 move () {
    console.log('move this circle with radius of ', this.size, ' to the position x = ', this.x, ' y = ', this.y);
 }

 draw() {
     console.log(this);
 }
}

const Circle = function(x, y, radius) {
  this.x = x;
  this.y = y;
  this.radius = radius;

 //instance method
 this.move = function() {
    console.log('move this circle with radius of ', this.radius, ' to the position x = ', this.x, ' y = ', this.y);
 }

 this.draw = function () {
    console.log(this)
 }
}

console.log('#########Square');
const s0 = new Square(0, 0, 10);
s0.draw();

const draws1 = s0.draw;
console.log(draws1);
draws1();

console.log('#########Circle');
const c0 = new Circle(0, 0, 10);
c0.draw();

const drawc1 = c0.draw;
console.log(drawc1);
drawc1();

collecting log messages and show only if an error happns

There should be feature in javascript console API that shows log messages only if this run cycle ends with an error.

Let’s say

console.onErrorLog("something"); // not shown
console.onErrorLog("something else"); // still not shown
invalidFnCall(); // now it shows everything that has been kept in buffer

So, normal flow never shows these messages.

What is best way to achieve this behavior?

Javascript Datatable Sum the amount

The amount of Sum is not getting displayed in footer, it is creating additional row and showing sum there. Where as it should be shown in the footer.

Result Image

function calculateColumn(index) {
  var total = 0;
  $('table tr').each(function() {
    var value = parseFloat(($('td', this).eq(index).text()).replace(/,/g, ""));
    if (!isNaN(value)) {
      total += value;
    }
  });
  $('table tfoot td').eq(index).text('Sum: ' + total);
}

$(document).ready(function() {
  var table = $('#example').DataTable({
    lengthChange: false,
    buttons: ['copy', 'excel', 'pdf'],
    paging: false,
    scrollY: 400
  });

  table.buttons().container()
    .appendTo('#example_wrapper .col-md-6:eq(0)');


  $('#example').on('draw.dt', function() {
    $('table thead th').each(function(i) {
      calculateColumn(i);
    });
  });

  $('table thead th').each(function(i) {
    calculateColumn(i);
  });
});
<!DOCTYPE html>
<html data-bs-theme="dark">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css" />
  <script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/buttons/1.6.2/js/dataTables.buttons.min.js"></script>
</head>

<body>

  <div class="table-responsive">
    <table id="example" class="table table-striped cell-border stripe table-bordered table-responsive-xl">

      <tbody>
        <tr>
          <td scope="row">15</td>
          <td>Test Account (1420240741161)</td>
          <td><a href="">-800</a></td>
          <td><a href="">-610.73</a></td>
        </tr>
        <tr>
          <td scope="row">16</td>
          <td>Testing Account (1620240781182)</td>
          <td><a href="">100</a></td>
          <td><a href="">40</a></td>
        </tr>

      </tbody>
      <tfoot>
        <tr class="totalColumn">
          <td style="visibility:hidden;"></td>
          <td style="visibility:hidden;"> </td>
          <td>Sum:</td>
          <td>Sum:</td>
        </tr>
      </tfoot>
    </table>
  </div>
</body>

</html>

Repeating text as not allowing to post:

The amount of Sum is not getting displayed in footer, it is creating additional row and showing sum there. Where as it should be shown in the footer.

Result Image

Nuxt 3 SSR user IP

how to transfer the client IP with SSR to the backend? Now I am transmitting the IP of the server on which the project is located

Global fetch configuration

import { ofetch } from 'ofetch';
import { defineNuxtPlugin } from '#app';

export default defineNuxtPlugin(() => {
  const headers = useRequestHeaders(['cookie']);
  globalThis.$fetch = ofetch.create({
    headers,
    credentials: 'include',
    retry: 0,
  });
});

Plugin for initializing a user session and obtaining his geo
geo.ts

import { useGeoStore } from '~/store/geo';


export default defineNuxtPlugin(async () => {
  const geoStore = useGeoStore();

  const { data: geo } = await useFetch('/api/v1/session', {
    baseURL: useRuntimeConfig().public.API_BASE_URL,
    headers: useRequestHeaders(['cookie']),
    watch: false
  });
});

Made a proxy layer for api requests

server/api/[…].ts

import { joinURL } from 'ufo';
import { defineEventHandler } from 'h3';

export default defineEventHandler((event) => {
  const config = useRuntimeConfig();
  return proxyRequest(event, joinURL(config.public.API_BASE_URL, event.path));
});

if I rename geo.ts and geo.client.ts then everything works correctly and the IP is transferred to the user

Best approach for showing custom data in the Volt template dashboard for Django

I am currently building a personal app and would like to use the Volt template for Django.

The link to the template is here:
https://tb-volt-dashboard-django.appseed-srv1.com/dashboard.html

I want to update the chart in the dashboard to use custom generated data from the view.

What’s the best approach/ recommended approach to do that?

I see currently that the data is being hard-coded in the volt.js file in the Volt directories.

What is ! before the variable does in javascript [duplicate]

what is the difference between
variable!.child_variable
and
variable?.child_variable

Use case Example

const data = obj!.data;

vs

const data = obj?.data;

Similar applied to func of that obj

obj!.doSomething();

vs

obj?.doSomething();

Note: this is not the same as In TypeScript, what is the ! (exclamation mark / bang) operator when dereferencing a member?

Here, we are discussing the differences.

It is the same for me. But still are there any differences?

Jest + ES Modules: “require is not defined” and “extensionsToTreatAsEsm” Errors

Issue with Jest Testing in Express App using ES Modules

I’m currently working on testing my Express app using Jest with ES Modules, but I am encountering a few issues during the test run.

The Problems:

  1. require is not defined — This error occurs when I try to mock my services using jest.mock(). Since I’m using ES modules (type: "module"), I can’t use require, and I’m unsure how to properly mock the services with ES module syntax.

  2. Validation Error:

    Option `extensionsToTreatAsEsm: ['.js']` includes '.js' which is always inferred.
    
    

I added extensionsToTreatAsEsm: [‘.js’] in Jest’s config to ensure .js files are treated as ES modules, but Jest is throwing this validation error, indicating it should be inferred automatically.

My Setup:
Node version: v18.20.4
Jest version: ^29.7.0
ESM support: Enabled with “type”: “module” in my package.json.
Configuration Files:

jest.config.js:

export default {
  transform: {
    '^.+\.js$': 'babel-jest',  // Using babel-jest to handle ES module transformation
  },
  testEnvironment: 'node',  // Set test environment to Node.js
  moduleFileExtensions: ['js', 'mjs'],  // Include ES module extensions
  moduleNameMapper: {
    '^(\.{1,2}/.*)\.js$': '$1',  // Map file extensions correctly for ESM
  },
};

babel.config.js:

export default {
  presets: [
    ['@babel/preset-env', { targets: { node: 'current' } }],  // Use Babel to transpile ES6+ code for current Node version
  ],
};

Test File (studentController.test.js):

import { jest } from '@jest/globals';
import request from 'supertest'; // Using supertest to test HTTP endpoints
import app from '../server.js'; // Importing the Express server
import { 
  fetchStudentsByTeacherId, 
  fetchStudentById, 
  createNewStudent, 
  updateExistingStudent, 
  processFileUpload 
} from '../services/studentService.js'; // Importing services

// Mock the service layer with ES module syntax
jest.mock('../services/studentService.js', () => ({
  fetchStudentsByTeacherId: jest.fn(),
  fetchStudentById: jest.fn(),
  createNewStudent: jest.fn(),
  updateExistingStudent: jest.fn(),
  processFileUpload: jest.fn(),
}));

describe('Student Controller', () => {
  describe('getStudentsByTeacher', () => {
    it('should fetch students for a teacher by teacher ID', async () => {
      const mockStudents = [{ firstName: 'John', lastName: 'Doe' }];
      fetchStudentsByTeacherId.mockResolvedValue(mockStudents);
      
      const res = await request(app).get('/students/by-teacher/teacher123');
      
      expect(res.status).toBe(200);
      expect(res.body).toEqual(mockStudents);
      expect(fetchStudentsByTeacherId).toHaveBeenCalledWith('teacher123');
    });

    it('should return 500 if an error occurs', async () => {
      fetchStudentsByTeacherId.mockRejectedValue(new Error('Failed to fetch students'));

      const res = await request(app).get('/students/by-teacher/teacher123');

      expect(res.status).toBe(500);
      expect(res.body.message).toBe('Server error');
    });
  });

  describe('getStudentById', () => {
    it('should fetch a student by student ID', async () => {
      const mockStudent = { firstName: 'John', lastName: 'Doe' };
      fetchStudentById.mockResolvedValue(mockStudent);

      const res = await request(app).get('/students/student123');
      
      expect(res.status).toBe(200);
      expect(res.body).toEqual(mockStudent);
      expect(fetchStudentById).toHaveBeenCalledWith('student123');
    });

    it('should return 500 if an error occurs', async () => {
      fetchStudentById.mockRejectedValue(new Error('Failed to fetch student'));

      const res = await request(app).get('/students/student123');

      expect(res.status).toBe(500);
      expect(res.body.message).toBe('Server error');
    });
  });

  describe('addStudent', () => {
    it('should add a new student and return a success message', async () => {
      const mockStudent = { firstName: 'John', lastName: 'Doe' };
      createNewStudent.mockResolvedValue(mockStudent);

      const studentData = {
        firstName: 'John',
        lastName: 'Doe',
        rollNumber: 123,
        class: 'class123',
        guardians: [{ firstName: 'Jane', isPrimaryContact: true }],
        photo: 'url',
      };

      const res = await request(app).post('/students/add').send(studentData);
      
      expect(res.status).toBe(201);
      expect(res.body.message).toBe('Student and guardians added successfully');
      expect(res.body.student).toEqual(mockStudent);
      expect(createNewStudent).toHaveBeenCalledWith(studentData);
    });

    it('should return 500 if an error occurs', async () => {
      createNewStudent.mockRejectedValue(new Error('Failed to add student'));

      const studentData = {
        firstName: 'John',
        lastName: 'Doe',
        rollNumber: 123,
        class: 'class123',
        guardians: [{ firstName: 'Jane', isPrimaryContact: true }],
        photo: 'url',
      };

      const res = await request(app).post('/students/add').send(studentData);
      
      expect(res.status).toBe(500);
      expect(res.body.message).toBe('Error adding student');
    });
  });

  describe('updateStudent', () => {
    it('should update a student and return a success message', async () => {
      const mockUpdatedStudent = { firstName: 'John', lastName: 'Doe', rollNumber: 123 };
      updateExistingStudent.mockResolvedValue(mockUpdatedStudent);

      const studentData = {
        firstName: 'John',
        lastName: 'Doe',
        rollNumber: 123,
        class: 'class123',
        guardians: [{ firstName: 'Jane', isPrimaryContact: true }],
        photo: 'url',
      };

      const res = await request(app).put('/students/edit/student123').send(studentData);
      
      expect(res.status).toBe(200);
      expect(res.body.message).toBe('Student and guardians updated successfully');
      expect(res.body.student).toEqual(mockUpdatedStudent);
      expect(updateExistingStudent).toHaveBeenCalledWith('student123', studentData);
    });

    it('should return 500 if an error occurs', async () => {
      updateExistingStudent.mockRejectedValue(new Error('Failed to update student'));

      const studentData = {
        firstName: 'John',
        lastName: 'Doe',
        rollNumber: 123,
        class: 'class123',
        guardians: [{ firstName: 'Jane', isPrimaryContact: true }],
        photo: 'url',
      };

      const res = await request(app).put('/students/edit/student123').send(studentData);

      expect(res.status).toBe(500);
      expect(res.body.message).toBe('Error updating student');
    });
  });

  describe('uploadStudentFile', () => {
    it('should process the student file upload and return a success message', async () => {
      processFileUpload.mockResolvedValue();

      const res = await request(app).post('/students/upload-student-file').send({ fileUrl: 'https://s3.amazonaws.com/file.csv' });

      expect(res.status).toBe(200);
      expect(res.body.message).toBe('Student file notification received, processing will start shortly.');
      expect(processFileUpload).toHaveBeenCalledWith('https://s3.amazonaws.com/file.csv', 'BULK_IMPORT_STUDENTS');
    });

    it('should return 500 if an error occurs', async () => {
      processFileUpload.mockRejectedValue(new Error('Failed to process file'));

      const res = await request(app).post('/students/upload-student-file').send({ fileUrl: 'https://s3.amazonaws.com/file.csv' });

      expect(res.status).toBe(500);
      expect(res.body.message).toBe('Error processing student file notification');
    });
  });
});

What I’ve Tried:

I’m using Jest with babel-jest to transform ES modules, and I’ve set up Babel to transpile ES6+ for the current Node version.
I included extensionsToTreatAsEsm: [‘.js’] in jest.config.js because I’m working with ES modules (type: “module” in my package.json).

Questions:

How can I mock the services in Jest when using ES modules?
How do I resolve the validation error related to extensionsToTreatAsEsm?

vue js user state management is not working properly on vue js 3

working with Laravel 10 and Vue js 3 with vuex 4. I have following mainapp.vue file specially manage for menu items as well.

<template>
  <div>
    <div v-if="$store.state.user">
      <!--========== ADMIN SIDE MENU one ========-->
      <div class="_1side_menu">
        <div class="_1side_menu_logo">
          <h3 style="text-align:center;">Logo Image</h3>
          <!--<img src="/img/logo.jpg" style="width: 108px;margin-left: 68px;"/>-->
        </div>

        <!--~~~~~~~~ MENU CONTENT ~~~~~~~~-->
        <div class="_1side_menu_content">
          <div class="_1side_menu_img_name">
            <p class="_1side_menu_name">Admin</p>
          </div>

          <!--~~~ MENU LIST ~~~~~~-->
          <div class="_1side_menu_list">
            <ul class="_1side_menu_list_ul">
              <li><router-link to="/"><Icon type="ios-speedometer" /> Dashboard</router-link></li>
              <li><router-link to="tags"><Icon type="ios-speedometer" /> Tags</router-link></li>
              <li><router-link to="category"><Icon type="ios-speedometer" /> Category</router-link></li>
              <li><router-link to="adminusers"><Icon type="ios-speedometer" /> Admin users</router-link></li>
              <li><a href="/logout"><Icon type="ios-speedometer" /> Logout</a></li>
            </ul>
          </div>
        </div>
      </div>
      <!--========== ADMIN SIDE MENU ========-->

      <!--========= HEADER ==========-->
      <div class="header">
        <div class="_2menu _box_shadow">
          <div class="_2menu_logo">
            <ul class="open_button">
              <li>
                <Icon type="ios-list" />
              </li>
            </ul>
          </div>
        </div>
      </div>
      <!--========= HEADER ==========-->
    </div>
    <router-view />
  </div>
</template>

<script>
export default {
    props: ['user'],
    data(){
       return {
          isLoggedIn : false, 
       }
    }, 
    created(){
       this.$store.commit('updateUser', this.user)
    }
}
</script>

my store.js file is

import { createStore } from 'vuex';

const store = createStore({
    state : {
        conuter : 1000, 
        deleteModalObj : {
            showDeleteModal: false, 
            deleteUrl : '', 
            data : null, 
            deletingIndex: -1, 
            isDeleted : false,

        }, 
        user: null, 
        
    }, 
    getters: {
        getCounter(state){
           return state.conuter
        }, 
        getDeleteModalObj(state){
            return state.deleteModalObj;
        },
       
      
        
    },

    mutations: {
        changeTheCounter(state, data){
            state.conuter += data
        }, 

        setDeleteModal(state, data){
            const deleteModalObj = {
                showDeleteModal: false, 
                deleteUrl : '', 
                data : null, 
                deletingIndex: -1, 
                isDeleted : data,
            }
            state.deleteModalObj = deleteModalObj
        },
        setDeletingModalObj(state, data){

            console.log('setDeletingModalObj mutation called');
        console.log('Data received:', JSON.parse(JSON.stringify(data))); // Convert Proxy to plain object for logging


            state.deleteModalObj = data

            console.log('Updated deleteModalObj state:', JSON.parse(JSON.stringify(state.deleteModalObj)));
        },
        updateUser(state, data){
            console.log('Updating user in Vuex:', data);
            state.user = data
        },
     }, 
     actions :{
        changeCounterAction({commit}, data){
            commit('changeTheCounter', data)
        }
    }

});

export default store;

I have following welcome.blade.php file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fullstack Blog</title>
    <link rel="stylesheet" href="/css/all.css">

    <script>
        (function () {
            window.Laravel = {
                csrfToken: '{{ csrf_token() }}',
                user: @json(Auth::user())
            };
            console.log('Laravel User:', window.Laravel.user);
        })();
    </script>
</head>
<body>
    
    <div id="app">
    <pre>{{ json_encode(Auth::user()) }}</pre>
    @if(Auth::check())
        <mainapp :user='@json(Auth::user())'></mainapp>
    @else
        <mainapp :user="false"></mainapp>
    @endif
</div>


    <script src="{{ mix('js/app.js') }}"></script>
</body>
</html>

but in my mainapp.vue file <div v-if="$store.state.user"> is not working it means not displaying my menu items and my console printing here but in welcome.blade.php file console.log('Laravel User:', window.Laravel.user); is printing current user object but mainapp.vue file console console.log('mainapp user',this.user); and store.js console.log('Updating user in Vuex:', data); is printing undefined how could I pass blade file user data to vue file via vuex

What am l missing here? [closed]

it’s the first time I’m posting here and i’m a beginner with API’s and I’m trying to make my own weather app. I can’t understand why is it not working. I believe there is a problem in my js code. Any thoughts or help?

const apiKey = '5e005f26bb4c4dd1a6b111343240510';
const apiUrl = 'http://api.weatherapi.com/v1/current.json?key={API_KEY}&q={CITY_NAME}';
const locationInput = document.getElementById('locationInput');
const searchButton = document.getElementById('searchButton');
const locationElement = document.getElementById('location');
const temperatureElement = document.getElementById('temperature');
const descriptionElement = document.getElementById('description');

searchButton.addEventListener('click', () => {
    const location = locationInput.value;
    if (location) {
        fetchWeather(location);
    }
});

function fetchWeather(location) {
    const url = `${apiUrl}?q=${location}&appid=${apiKey}&units=metric`;

    fetch(url)
        .then(response => response.json())
        .then(data => {
            locationElement.textContent = data.name;
            temperatureElement.textContent = `${Math.round(data.main.temp)}°C`;
            descriptionElement.textContent = data.weather[0].description;
        })
        .catch(error => {
            console.error('Error fetching weather data:', error);
        });
}

I’ve tried regenerate my API key but still nothing. It just doesn’t work.

change value of input type range… dont work same change with mouse

I have 13 inputs type range. The initial value are 0

I can change the values with the mouse for example…. how i can do to change its parameters but with javascript for example, because if i change the values using id and val() and .change() the values changes… but dont wotk the funtions if i do it with mouse…

<input type="range" min="-13" max="13" class="rechancices" id="qwe1253">
<input type="range" min="-13" max="13" class="rechancices" id="qwe1254">
<input type="range" min="-13" max="13" class="rechancices" id="qwe1255">
<input type="range" min="-13" max="13" class="rechancices" id="qwe1256">
<input type="range" min="-13" max="13" class="rechancices" id="qwe1257">

$("#qwe1251").val(13).change.

.. change the value, but dont work any event…

solution with javascrit to change inputs range values

Drop down menu not functioning properly

I’m working on the reponsiveness of my site using media queries. when i click on the icon, the menu drops but when i click agaiin to return… it doesn’t return.

my html code

<nav>
  <img src="../images/shotbyopi.logo (5).png" alt="logoPic" />
  <ul id="sidemenu">
    <li><a href="#">Home</a></li>
    <hr />
    <li><a href="#about-1">About</a></li>
    <hr />
    <li><a href="#wrapper">Services</a></li>
    <hr />
    <li><a href="#contact">Contact</a></li>
  </ul>
  <i class="fa-solid fa-circle-chevron-down" onclick="toggleMenu()"></i>
</nav>

This is my css for the specific screens i’m working on

@media (min-width: 481px) and (max-width: 768px) {
  nav .fa-circle-chevron-down {
    display: block;
    font-size: 85px;
    position: fixed;
    top: 20px;
    right: 20px;
    color: transparent;
    -webkit-text-stroke: 4px #fff;
    z-index: -2;
    transition: transform 0.5s ease-in-out;
    margin-top: 60px;
    cursor: pointer;
  }

  nav img {
    width: 325px;
    height: 325px;
  }

  nav .fa-solid:hover {
    transform: translateY(-10px);
    transform: rotate(90deg);
  }

  nav ul {
    display: flex;
    flex-direction: column;
    row-gap: 20px;
    margin-left: 0;
    background: transparent;
    position: fixed;
    text-align: center;
    margin-top: 20px;
    top: -100vh;
    left: 0;
    width: 27%;
    height: 100vh;
    padding: 50px 20px;
    z-index: 2;
    transform: translateX(230%);
    transition: top 0.5s ease-in-out;
  }

  /* When the menu is active */
  nav ul.show-menu {
    top: 0; /* Slide down into view */
  }

  /* Styling for individual list items */
  nav ul li {
    margin: 5px 0;
    font-size: 1.5rem;
  }

  /* Make sure links are styled clearly */
  nav ul li a {
    color: white;
    text-decoration: none;
  }
}

The provided CSS code seems to be styling a navigation element (nav) with a menu icon and a list of items.

my javascript code for the functionality of the menu bar


function toggleMenu() {
    const menu = document.getElementById('sidemenu');
    const toggleIcon = document.querySelector('.toggle-menu');
  
    menu.classList.toggle('show-menu');
    toggleIcon.classList.toggle('rotate');
  }
  
  document.addEventListener('DOMContentLoaded', () => {
    const toggleIcon = document.querySelector('.toggle-menu');
  
    if (toggleIcon) {
      toggleIcon.addEventListener('click', toggleMenu);
    } else {
      console.error('Element with class "toggle-menu" not found.');
    }
  });

I tried to get a correction from Gemini AI, but it began to show me errors, below is the javascript code

function toggleMenu() {
  const menu = document.getElementById('sidemenu');
  const toggleIcon = document.querySelector('.toggle-menu');

  menu.classList.toggle('show-menu');
  toggleIcon.classList.toggle('rotate');
}

document.addEventListener('DOMContentLoaded', () => {
  const toggleIcon = document.querySelector('.toggle-menu');

  if (toggleIcon) {
    toggleIcon.addEventListener('click', toggleMenu);
  } else {
    console.error('Element with class "toggle-menu" not found.');
  }
});

How to extend a class if declared this way

For a certain reason, I have to declare my classes this way:

const core = {
    character: class {
        constructor(arg) {}
    }
}

Works pretty, but I don’t know how to extends the class ‘character’. I’m trying the way below, but it doesn’t work:

const core = {
  character: class {
    constructor(arg) {}
  },
  enemy: class extends core.character {
    constructor(arg) {}
  }
}