In my current project, I am working with Knockout and TypeScript but I am encountering difficulties in firing the window-resize event

Instead of using jquery, I prefer working with a custom handler for the $(window).resize(function () { ... event.

If there is a way to achieve this without relying on jquery, please feel free to share it in the comments below.

The code snippet below shows that the resize event couldn't bind when placed in my app-root.cshtml:

app-root.cshtml

<app-root></app-root>

<template id="app-root-template">
    <div data-bind="event: { resize: mainWindowResize }">
        <partial name="nav-menu/nav-menu" />
        <div class="row">
            <div class="col-sm-12">
                <partial name="error-message/error-message" />
            </div>
            <div>

            </div>
        </div>
    </div>
</template>

app-root-viewmodel.ts

import ko from "knockout";
import { registerComponent } from "../../infrastructure/register-component";

/**
 * Application Root
 *   Provides an application root container for components
 */
class AppRootViewModel {
    constructor() {

        registerComponent("nav-menu");
        registerComponent("error-message");

}

    public mainWindowResize = () => {
        console.log("Window resize");
    }

}

export default {
    template: { element: "app-root-template" },
    viewModel: AppRootViewModel
};

Thank you in advance for your assistance :)

Answer №1

The div element does not support the window resize event. This event is only supported on the body tag. You can add the resize event to your window without using jQuery by following this code snippet:

window.addEventListener('resize', /* your function here */);

Adding this functionality in your AppViewModel goes against the MVVM pattern, as it involves mixing view logic with ViewModel. Knockout provides a solution for this issue through bindingHandlers or customBinding. By utilizing a bindingHandler, you can register the resize event on the window within your div element and call your desired function from there. Here's an example:

BindingHandler:

ko.bindingHandlers.windowResize = {
    init: function(element, valueAccessor) {
        const callback = valueAccessor();
        window.addEventListener('resize', callback);

        ko.utils.domNodeDisposal.addDisposeCallback(element, () => {
            window.removeEventListener('resize', callback);
        });
    }
};

Your HTML:

<app-root></app-root>

<template id="app-root-template">
    <div data-bind="windowResize: mainWindowResize">
        <partial name="nav-menu/nav-menu" />
        <div class="row">
            <div class="col-sm-12">
                <partial name="error-message/error-message" />
            </div>
            <div>

            </div>
        </div>
    </div>
</template>

Check out this JSFiddle example for a demonstration: https://jsfiddle.net/FleMo/2h9s586k/2/

Edit: included a link to a JSFiddle demo

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

How can the value be accessed when using getElementById in Angular for <mat-select> elements that do not have a value attribute?

Within a loop, I have an element that has a dynamically generated id: <mat-select multiple class="dw-input" [value]="element.txn_type_id ? element.txn_type_id.split(',') : []" id="field-{{element.Name}}-txn_type_id&quo ...

Using jQuery, you can easily update the value of the nth-child(n) for a cloned element

Looking to duplicate an HTML element and assign new values to its child elements? Here's my current HTML structure: <div id="avator" class="avator" style="display:none"> <label><a href="/cdn-cgi/l/email-protection" class="__cf_email ...

Issue with Authentication - Sequencing of Observables and Promises in Angular/REST APIs

I'm currently utilizing Angular 7 and have recently started working on a new Angular application project at my agency. One of my colleagues has already set up the backend (Restful), so I began by focusing on implementing the Authentication Feature. T ...

Managing window popups using WDIO - tips and tricks

Having some trouble handling a facebook auth dialog popup through webdriverio. Struggling to target the email and password fields for the facebook signup process. Below is the code in question: it('redirects after signup', () => { browse ...

Setting a default value within an input tag: A step-by-step guide

const [userData, setUserData] = useState([]); const handleUserInfo = (id) => { fetch(`https://602e7c2c4410730017c50b9d.mockapi.io/users/${id}`) .then(res => res.json()) .then(data => setUserData(data)) } <inpu ...

Transferring Files from Bower to Library Directory in ASP.Net Core Web Application

Exploring ASP.Net Core + NPM for the first time, I have been trying out different online tutorials. However, most of them don't seem to work completely as expected, including the current one that I am working on. I'm facing an issue where Bower ...

Node.js Express post query failing to set content type

I have a POST request implemented with the express framework to submit a query to a rest api. Here is the relevant code snippet: var request = require('request'); app.post('/compute', function(req, postResponse) { var queryJSON = re ...

Automatically select a radio button upon loading the page

Below is the code I am currently using: jQuery('#choice_1_10_3_1').attr('checked','checked'); I need this radio button to be checked automatically when the page loads. Despite no errors being shown in the console, the code i ...

creating a personalized tooltip for every item within a dynamically generated @html.dropdownfor control in mvc3

Currently, I am developing a web project using MVC 3 and Razor in C#. In my code, I have implemented @Html.DropDownListFor to dynamically display items. Now, I would like to add tooltips for each item displayed by @Html.DropDownListFor. Here is the relev ...

Shortening a jQuery If-Else Statement in JavaScript

I am working on a snippet of code and need some help. Here is the code: <script type="text/javascript"> $(window).load(function() { if(!$.browser.msie){ $('#myDiv').animate({opacity: 1}, 300); } else if ($.browser.msie) { ...

Enhancing User Experience with Animated jQuery Progress Bar

I came across a cool tutorial on animating progress bars: The only issue was that the progress bar didn't utilize jquery, and there wasn't information on linking multiple buttons to it. After some searching, I found another tutorial that address ...

the object '[object Object]' of a distinct supporting nature

I encountered an error stating "ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays." This is my TypeScript file: this.list = data.json(); ...

Issue with the useSWR hook causing the DOM not to update correctly due to mutation

My next.js app is utilizing the `useSWR` hook to fetch and populate data. const { data, error } = useSWR('/api/digest', fetcher, { revalidateOnFocus: false, }) The problem I am facing is that the DOM is not updating as expected after the `mu ...

Developing a standard jQuery function for adding event listeners

Attempting to replicate the functionality of Google Maps' addListener using jQuery listeners for clicks, keypresses, etc. In Moogle Maps, you can use .event.addListener(map, 'click', function()... or switch 'click' with 'drag ...

Is there a way to sort data by year and month in mongodb?

I'm trying to filter data by year in MongoDB based on a specific year and month. For example, if I pass in the year 2022, I only want to see data from that year. However, when I try using the $gte and $lte tags, it returns empty results. Can someone g ...

Checking if the current time falls within a specific range while also taking minutes into account

I am currently working on a website for restaurants offering home delivery services. I need to enable or disable the 'Order Now' button based on the designated home delivery timings of each restaurant. For this purpose, I have access to the star ...

AJAX requires manual updating by clicking on a button

I've created a chat system where two individuals can communicate with each other. An AJAX function has been implemented to update the message container every 2 seconds. However, I have noticed that the AJAX call doesn't run immediately after a u ...

Utilizing node.js as a standalone web server application

I've developed a node.js-based web server (Javascript file) designed to serve a Javascript-integrated web page for controlling immersive sound on mobile devices. The server utilizes native modules for MIDI and pcap communication, along with express fo ...

What is the best way to resume a paused animation using JavaScript?

My first game involves triggering an animation that transitions the game screen to greyscale when the character dies. Despite my efforts, I have been unable to successfully trigger this animation using document.getElementById("object").animationP ...

Unable to install react-dom/test-utils using npm

I recently included two libraries in my package.json "devDependencies": { ... "react-dom/test-utils": "*", "react-test-renderer/shallow": "*" }, These were recommended by the React documentation to align with version 16 of the React ecosy ...