Struggling with TypeScript and JsObservable? Let us assist you!

Having previous experience with JSRender, JSViews, and JSObservables, I recently embarked on a new project using TypeScript. Unfortunately, I am struggling to understand how to properly utilize TypeScript in my project, especially when it comes to referencing .js, .d.ts, and .ts files.

If I could provide details about what I currently have, where it is failing, and receive some guidance from you, it would greatly help me kickstart this project!

The contents of my "scripts" folder include the following files:


~\Typings\jQuery\jQuery.d.ts
installed from the NuGet package: jquery.TypeScript.DefinitelyTyped v0.0.1

~\Typings\jsrender\jsrender.d.ts   
installed from the NuGet package: jsrender.TypeScript.DefinitelyTyped v0.1.8

File: ~/index.html


<!DOCTYPE html>
<html lang="en">
<head>
    <script src="scripts/jquery-3.1.1.js"></script>
    <script src="scripts/jsviews.js"></script>
    <script src="scripts/game/game.js"></script>
    <script src="scripts/game/app.js"></script>
</head>
<body>
    <div id="view">
        <div id="myMap"></div>
        <div id="optionsTmpl"></div>
    </div>
</body>
</html>

File: ~/tmpl/options.tmpl.html


<div class="optionsFrame">
    <select data-link="mapType">
    {^{for mapTypes}}
        <option value="{{:id}}">{{:name}}</option>
    {{/for}}
    </select>
    <input type="button" value="test">
</div>

File: app.ts


/// <reference path="../typings/jquery/jquery.d.ts" />
/// <reference path="../typings/jsrender/jsrender.d.ts" />
class UnchartedApp {
    game: UnchartedGame;

    init() {
        this.game = new UnchartedGame();
        this.game.loadMap();
    }
}

window.onload = () => {
    var app = new UnchartedApp();
    app.init();
};

File: game.ts


/// <reference path="../typings/jquery/jquery.d.ts" />
/// <reference path="../typings/jsrender/jsrender.d.ts" />
class UnchartedGame {
    constructor() {}

    /***** Error on the $.observe() line !! *****/
    loadMap() {
        this.linkTemplate("options", "#optionsTmpl", this).done(function (currentGame) {
            $.observe(currentGame, "*", currentGame.modelChangeHandler);
        });
    }

    modelChangeHandler(ev, eventArgs) {
        if (ev.type == "propertyChange") {
            var _game: UnchartedGame = ev.currentTarget;
            if (eventArgs.path == "mapType") {
                try {
                    _game.myMap.setMapType(mapTypeNames[newValue]);
                } catch (ex) {}
            }
        }
    }

    loadTemplate(tmplName: string) {
        var deferredLoad = $.Deferred();
        try {
            var filePath: string = "../tmpl/" + tmplName + ".tmpl.html";
            $.get(filePath).then(function (templateText) {
                $.templates(tmplName, templateText);
                deferredLoad.resolve();
            })
        } catch (e) {
            deferredLoad.reject();
        }
        return deferredLoad.promise();
    }

    linkTemplate(tmplName: string, targetId: string, model: UnchartedGame) {
        var deferredLink = $.Deferred();
        try {
            this.loadTemplate(tmplName).done(
            function () {
                $.templates[tmplName].link(targetId, model);
                deferredLink.resolve(model);
            });
        } catch (e) {
            deferredLink.reject();
        }
        return deferredLink.promise();
    }
}

Thanks for your assistance,

Claude

Answer №1

TypeScript emphasizes the usage of ES6 import statements, for example:

import * as jQuery from 'jquery';
An alternative approach is to include the script (e.g. jquery) in your module loader and then declare const jQuery: any for widespread use across your application. Another method involves referencing typings in your tsconfig file:

First method using import statements:

import * as jQuery from 'jquery'; // jquery installed via npm install jquery
import * as jsrender from 'jsrender'; // jsrender installed via npm install jsrender

// === OR ===

declare const jQuery: any; // Reference the script in your module loader/html
declare const jsrender: any; // Reference the script in your module loader/html

class UnchartedGame {
    constructor() {
    }


/*****      Error on the $.observe() line !!    *****/
loadMap() {
    this.linkTemplate("options", "#optionsTmpl", this).done(function (currentGame) {
        $.observe(currentGame, "*", currentGame.modelChangeHandler);
    });
}

modelChangeHandler(ev, eventArgs) {
    if (ev.type == "propertyChange") {
        var _game: UnchartedGame = ev.currentTarget;
        if (eventArgs.path == "mapType") {
            try {
                _game.myMap.setMapType(mapTypeNames[newValue]);
            }
            catch (ex) {
            }
        }
    }
}

loadTemplate(tmplName: string) {
    var deferredLoad = $.Deferred();
    try {
        var filePath: string = "../tmpl/" + tmplName + ".tmpl.html";
        $.get(filePath).then(function (templateText) {
            $.templates(tmplName, templateText);
            deferredLoad.resolve();
        })
    }
    catch (e) {
        deferredLoad.reject();
    }
    return deferredLoad.promise();
}

linkTemplate(tmplName: string, targetId: string, model: UnchartedGame) {
    var deferredLink = $.Deferred();
    try {
        this.loadTemplate(tmplName).done(
        function () {
            $.templates[tmplName].link(targetId, model);
            deferredLink.resolve(model);
        });
    }
    catch (e) {
        deferredLink.reject();
    }
    return deferredLink.promise();
}

}

Using TSConfig:

{
  "compilerOptions": {
    "types": ["jquery", "jsrender"]
  }
}

Another potential approach is to navigate to your main module and add this line:

import 'jquery'; // jquery installed via npm install jquery

I have observed that this method is efficient in one of my projects (requiring @types file).

Additionally, I suggest moving away from reference paths as TypeScript functions based on types. Most modules typically come with a typings file, although jQuery does not. Therefore, after installing jQuery with npm install jquery, consider installing its typings by executing

npm install @types/jquery --save-dev

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

The JavaScript functions are not loading within the onload event handler

I've got an HTML document that contains some Script sections. I've consolidated all the functions within a single Script Tag. Now, I want to be able to utilize these methods in both the onload and onclick events. Below is the HTML file with all t ...

Experience the dynamic live preview feature of Sanity integrated with NextJS 13

I am facing an issue with checking if preview mode is activated on my website. While following a YouTube tutorial, I realized that the instructions may be outdated with the latest NextJS update. This was the code snippet I was originally working with to ...

What is causing `foo()` to function in this specific scenario?

Check out this code snippet: https://jsfiddle.net/5k10h27j/ I'm puzzled by why foo() is being called as an argument to a non-existent function. function foo(){ alert('huh??'); } jQuery('#container').on('change', ...

What is the ideal event to trigger a response when the user completes entering text into the search field in Vue.js?

I am currently utilizing a text field from the Vuetify library to filter a table within my application. <v-text-field style="min-width: 300px;" v-model="filterString" label="Search" /> The functionality is straigh ...

When trying to add a react-bootstrap modal, the react app crashes abruptly

Encountering errors while attempting to integrate react-bootstrap Modal component into my react project: ERROR in ./~/react-dom/lib/ReactDOMUnknownPropertyHook.js Module not found: Error: Cannot resolve module 'react/lib/ReactComponentTreeHook' ...

What are some ways to sort through JSON data efficiently?

I am in need of filtering JSON data based on specific parameters. When using the GET method at http://localhost:5000/api/car?bodyTypeId=2, I expect to receive only JSON objects with bodyTypeId equal to 2. However, all objects are being returned: [ { ...

What is the process for integrating custom event information stored in the {} property of a highchart dataset into highcharts-vue?

Creating charts with Vue using JSON data passed into the :options tag has been my usual approach. However, I am now experimenting with constructing a custom chart by utilizing the renderer and ren.path().attr().add() functions. The load function within th ...

Codeigniter dropdown sending incorrect value to controller

When I choose an option from the dropdown list and click the submit button in the modal, the selected value is not being posted to the controller as expected. Below is my view code: <div class="form-group"> <div class="col-md-4"> ...

Modify the PrimeFaces dialog to be modal using client-side code

One of my primefaces dialogs is set up like this: <p:dialog widgetVar="dlg" width="320" height="220" modal="false" closable="false" showHeader="false" resizable="false" position="right,top"> I am looking to make this dialog modal if a certain eleme ...

Creating a dropdown menu with data loaded dynamically using ajax and json, all without relying on jquery

I am looking to populate a few select menus using JSON data retrieved from my PHP script. Each select menu should display different values based on the selections made in the other menus. While I understand how to clear and fill a select menu using JavaScr ...

Error: req.next is not a recognized function in node.js

I am completely stumped by this sudden issue that just appeared out of nowhere, with no changes in the code! TypeError: req.next is not a function The error is occurring at line 120. Here is the corresponding SQL query and the problematic line 120: // Set ...

Unable to retrieve any response data in Angular 2

I'm having trouble retrieving the response from my API. Despite being able to do so with PostMan, my variable "this.data" remains null. I've experimented with various approaches to no avail. Any assistance would be greatly appreciated. The method ...

The term 'Employee' is typically used as a classification, but in this context, it is being treated as a specific value

I am encountering an issue while trying to define a variable as type Employee. The error message 'Employee' only refers to a type but is being used as a value here. ts(2693) keeps appearing. Here is my show-api.ts code: import { Component, OnIni ...

Error: Unable to locate module adaptivecards-templating

After adding the module through the command: npm install adaptive-expressions adaptivecards-templating --save and importing it, I encountered an error when trying to run my application: ...

Having trouble configuring AJAX and PHP to work together

Here's the situation I'm dealing with: I have HTML, JS, and PHP files. In the PHP file, there is an associative array containing default values to populate form elements in the HTML file. I'm trying to use AJAX to retrieve data from the PHP ...

Problem with selecting odd and even div elements

I have a div populated with a list of rows, and I want to alternate the row colors. To achieve this, I am using the following code: $('#PlatformErrorsTableData').html(table1Html); $('#PlatformErrorsTableData div:nth-child(even)').css(" ...

Simple steps to convert Redux state to Redux Persist with the help of 'combineReducers' function

I'm facing a challenge trying to implement Redux-Persist with my Redux state, particularly because I am using combineReducers. Here is the structure of my store: import { createStore, combineReducers } from 'redux' import { usersReducer } fr ...

Displaying a specific division solely on mobile devices with jQuery

I need to implement a feature where clicking on a phone number div triggers a call. However, I only want this div to be displayed on mobile devices. To achieve this, I initially set the div to "display:none" and tried using jQuery to show it on mobile devi ...

Error message: Laravel unable to locate requested page

Attempting to make a post request using AngularJS in Laravel, I encountered the following error message: Oops! The page you are trying to access could not be found. JAVASCRIPT app.controller('main',['$scope','$http',&apos ...

Why might the Bootstrap menu be malfunctioning?

The reality is that Bootstrap is functional and widely used. Sharing the code could make a big difference in getting assistance! <ul class="top-header-contact-info secondary-menu"> <li class="nav-item dropdown-toggle"> ...