Using Typescript and Knockout.js in an MVC application: A simplified guide

Having Trouble Binding a Knockout.js ViewModel to MVC

Despite attempting to follow multiple tutorials, none of them seem to be working for me. I have not encountered any errors while building the app, but the results are not as expected.

Here is my TS file:

/// <reference path="../typings/knockout/knockout.d.ts" />
/// <reference path="../typings/jquery/jquery.d.ts" />

export module HopCRM {
    export class ContactViewModel {
        text: string = "Test";
        public test: KnockoutObservable<string>;

    constructor() {
        console.log("hello")
        this.test = ko.observable("Test testing testing")

    }             
}

}

And here is my CSHTML:

<h2 data-bind="text: test">Waiting for viewModel</h2>

<script src="~/Scripts/Typescript/ContactViewModel.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1        /jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-min.js"></script>

<script type="text/javascript">
    var viewModel;
    (function () {
        viewModel = new HopCRM.ContactViewModel();
        ko.applyBindings(viewModel);  
    });
</script>

I was expecting a binding from 'public test' or at least a simple console.log statement to appear.

Answer №1

To implement export and modules, it is necessary to utilize webpack. If you prefer simplicity, you can use classes without export/imports:

Your TypeScript file:

class ContactViewModel {
        text: string = "Test";
        public test: KnockoutObservable<string>;

    constructor() {
        console.log("hello")
        this.test = ko.observable("Test testing testing")

    }             
}

Usage(in cshtml):

const viewModel = new ContactViewModel();
ko.applyBindings(viewModel);

Check out my working example here: https://jsfiddle.net/koljada/dgnyspwa/3/

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

What is the best way to stay on track with internal anchor links when navigating with Aurelia?

I'm currently working on developing a style guide for a project and one of the features I would like to implement is a basic click behavior on anchor links, allowing them to smoothly scroll to the corresponding section on the page. For instance: < ...

Angular 6 - execute function on either click event OR focus event

I am trying to figure out how to call a function from a component only when it is clicked or focused. Below is a snippet of the components HTML: <div class="form-add-new__input-box"> <input #commentCategories class="for ...

Unexpected data being passed in knockout click event binding

for (let i = 0; i < 9; i++) { vm.icdCodes.push({Index:i, ID:'',DiagnosisCd: '' ,Description:ko.observable('')}); } <tbody data-bind='foreach: $root.icdCodes'> <tr> <td> ...

The process of subscribing to a service in Angular

I currently have 3 objects: - The initial component - A connection service - The secondary component When the initial component is folded/expanded, it should trigger the expansion/folding of the secondary component through the service. Within the service ...

Change a TypeScript alias within the @types namespace

While using Typescript 3, I encountered a situation where I needed to modify a type alias from the @types/json-schema definition provided by DefinitelyTyped. The issue arose when I wanted to incorporate a custom schema type into my code. Since this custom ...

Searching for particular information within an array of objects

Seeking guidance as a newbie on how to extract a specific object from an array. Here is an example of the Array I am dealing with: data { "orderid": 5, "orderdate": "testurl.com", "username": "chris", "email": "", "userinfo": [ ...

Inheriting an Angular 5 class with injected dependencies

I recently defined a new class @Injectable FooService { constructor(private _bar:BarService){ } } Then I decided to extend it in the following way @Injectable ExtFooService extends FooService { constructor(private _bar:BarService){ ...

Using ngx-bootstrap typeahead with custom itemTemplate for objects

I've created a custom ngx-bootstrap/typeahead component for my ngx-formly generated forms. This component fetches search results from an API and is designed to be reusable for various objects, making it dynamic. My goal is to have the typeahead retri ...

Using redux action in the onPaginationChange function instead of setPaginationState in the given example for the TanStack table - is there a way to

Provided this sample Is there a way to utilize by dispatching a redux action rather than using useState - setPaginationState? onPaginationChange: state => dispatch(browseItemModalActions.setPagination(state)) An error is appearing in the console: ...

When using the .concat method on an array, props may display as unidentified

When I log the items array in my props, it contains items. However, when I try to add to the array using .concat, I encounter an error stating Cannot read property 'concat' of undefined export default (props) => { const { items } = props; ...

Retrieve active route information from another component

We are utilizing a component (ka-cockpit-panel) that is not linked to any route and manually inserted into another component like so: .. ... <section class="ka-cockpit-panel cockpit-1 pull-left"> <ka-cockpit-panel></ka- ...

Create a fresh type by dynamically adjusting/filtering its attributes

Suppose we have a type defined as follows: type PromiseFunc = () => Promise<unknown>; type A = { key1: string; key2: string; key3: PromiseFunc; key4: string; key5: PromiseFunc; key6: SomeOtherType1[]; key7: SomeOtherType2[]; key8: ...

React's useState feature is doubling the increment

I have created a basic form management system with a historical feature. A simplified version of this system can be seen on codesandbox import { useState } from "react"; import "./styles.css"; const sample = ["what", "w ...

Angular 2 Mixup: Using Leaflet and Google Maps with Incorrect Tile Order

I am encountering an issue while working on Leaflet and Google within Angular 2. The problem lies in the Tilemill tiles not rendering properly as they are displaying in a strange order. Here is a screenshot of the current state: https://i.stack.imgur.com/ ...

In Typescript, we can streamline this code by assigning a default value of `true` to `this.active` if `data.active

I am curious if there is a better way to write the statement mentioned in the title. Could it be improved with this.active = data.active || true? ...

Angular 4: Retrieving the selected element's object from a collection of elements

In my x.component.html file, I have a list of objects that are being displayed in Bootstrap cards like this: <div *ngFor="let item of items | async"> <div class="row"> <div class="col-lg-6"> <div class="card ...

An error in Typescript is indicating that a semicolon is expected. The identifier 'EventNameString' is currently being used as a value, even though it only refers to a type

I've been working on integrating Firebase phone authentication into an older Ionic project and have followed several tutorials. I was able to successfully implement it, but whenever I run ionic serve -l, I encounter the following error: Interestingly ...

Does moment/moment-timezone have a feature that allows for the conversion of a timezone name into a more easily comprehendible format?

Consider this example project where a timezone name needs to be converted to a more readable format. For instance: input: America/Los_Angeles output: America Los Angeles While "America/Los_Angeles" may seem human-readable, the requirement is to convert ...

Can you explain the distinction between Observable<ObservedValueOf<Type>> versus Observable<Type> in TypeScript?

While working on an Angular 2+ project in Typescript, I've noticed that my IDE is warning me about the return type of a function being either Observable<ObservedValueOf<Type>> or Observable<Type>. I tried looking up information abou ...

Display a list of items using *ngFor in a dropdown menu without using the optgroup

Is there a way to group data from *ngFor in the dropdown selection without using optGroup? You can find the JSON file link below: JSON Data Typescript Code getProducts() { if (this.products.length < 1) { this.productService.getProducts ...