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

Webmatrix - Retaining query parameters throughout the website's pages

After successfully implementing pagination on my search page, I ran into an issue where the query strings used to build the search query are lost when transitioning between pages. Is there a simpler way to retain these query strings, or will I have to delv ...

Guide on accessing values from an array of objects in JavaScript/Node.js

I am working with an array of objects that looks like this: const objArray = [{prop: "a", prop2 : "1"}, {prop: "b", prop2 : "2"}, {prop: "c"}, prop2 : "3"] My goal is to extract the property names of the objects in the array, rather than their values. D ...

MVC3 does not support JQuery UI

Just recently, I had all my jquery-ui elements functioning perfectly. However, now it seems that none of the jquery-ui features are working anymore. In my Site.Master page, I have included the following code... <link href="../../Content/Site.css" rel=" ...

The lightSlider is only destroyed and rebuilt once during its operation

I am facing a challenge with multiple buttons having the same class while trying to destroy and rebuild the lightSlider script. In the CMS where I have implemented this, images and ajax are being loaded. However, as the JavaScript is triggered by the read ...

What methods can be implemented to ensure ComponentOverride's universality?

These type definitions for markdown-to-jsx don't seem to be generic enough, causing issues like the one mentioned below. For more details, refer to Why is type SFC<AnchorProps> not assignable to type SFC<{}>? /Users/sunknudsen/Sites/sunk ...

Deleting uploaded images in Cloudinary for Next.js is not allowed

After successfully implementing image uploads in cloudinary for Next.js, I encountered an issue with image deletion. Despite creating the necessary routes and components, the deletion functionality is not working as expected. I am unsure of what could be ...

Tips for updating a reactive form with multiple layers of nested JSON values

I am tasked with retrieving and working with the data from a deeply nested (potentially infinite levels) reactive form that includes formArrays, formGroups, and formControls. This data is stored in a database. Currently, my approach involves patching the ...

I encountered an issue while trying to use jshint with a simple hello world script, receiving the error message: "line 0, col 0, Bad option: 'script'."

This is a basic introduction to my coding journey. function greet() { return 'Hello world'; } Here is the jshint setup I am using: { "browser": true, "browserify": true, "devel": true, "script" ...

Execute the code only if the variable is not null

I encountered an issue with my code: setInterval(function() { $.ajax({ url: url, success: function(data, count){ var obj = jQuery.parseJSON(data); var content = obj.results[0].content; }}) }, 2000) The code runs every 2 seconds an ...

Navigate to all hyperlinks in browser without the use of jQuery - specifically for Firefox OS

I stumbled upon this interesting solution on a programming forum. I'm curious, how does this code work without relying on jquery? $('a[href^=http]').click(function(e){ e.preventDefault(); var activity = new MozActivity({ name: ...

Is there a way to reset my div back to its initial background color when clicked a second time?

I am currently utilizing the jQuery addClass and removeClass animate feature for my project. Basically, what is happening is that when the user clicks on a particular link, a dropdown navigation will appear. This feature is essential for ensuring responsi ...

Introducing the concept of type-specific name inclusion

I am currently developing my Angular app using TypeScript with the goal of preventing redundancy through some form of generic handling. Here is where I am starting: class BaseProvider { api_url = 'http://localhost:80/api/FILL_OUT_PATH/:id&apo ...

Eliminate certain inline styles using jQuery

I am facing an issue with an asp menu I am using. It is automatically inserting style="width:3px;" into my menu table tds, creating an unsightly gap between my tabs. Instead of asking our developer to customize the menu just to fix this cosmetic flaw, I am ...

A guide on creating a Utility function that retrieves all elements in an array starting from the third element

I've been working on a tool to extract elements from an array starting after the first 2 elements. Although I attempted it this way, I keep getting undefined as the result. // ARRAYS var arr = ['one', 'two', 'three', &a ...

Utilizing regular expressions to find the attribute name within nested array brackets by matching the index number

Can someone assist me with RegEx? I am trying to extract only the index number found within brackets [1] in a string that looks like this: text[alphanumeric][index][text]. Please see the example attribute name below. name="lorem[ipsum_dolor_set-amet-34][1 ...

Prevent Android WebView from attempting to fetch or capture resources such as CSS when using loadData() method

Context To many, this situation might appear to be repetitive. However, I assure you that it is not. My objective is to import html data into a WebView, while being able to intercept user hyperlink requests. During this process, I came across this helpfu ...

Front-end procedural logic for increasing identification values

$scope.items.push({ "itemId": $scope.tabId + 1, "itemName" : itemName, }); Whenever I try to push the item, I always console.log($scope.itemId) but it remains the same without increasing. One way to handle this issue could be utilizing $http after each ...

The Ajax script seems to be failing to update the PHP file along with its corresponding variable value

I have a simple form where upon clicking the "=" button, I want the calculated value to be displayed in file process.php. However, this functionality is not working for me. It seems that when the "=" button is clicked, nothing happens. The default value in ...

How to Test React Js API Calls with Jest?

I'm currently in the process of writing test cases for my API call function, but I'm encountering difficulties as I am unable to successfully run my tests. Below is the code for the API call function and the corresponding test cases. export async ...

Utilize the npm module directly in your codebase

I am seeking guidance on how to import the source code from vue-form-generator in order to make some modifications. As a newcomer to Node and Javascript, I am feeling quite lost. Can someone assist me with the necessary steps? Since my Vue project utilize ...