TypeScript - referencing jQuery in classes

178 views Asked by At

Getting the following error "Uncaught ReferenceError: $ is not defined". I understand the error very well, jQuery isn't recognized inside my class. What I don't understand is how to ensure it gets picked up.

Here is what I've got so far:

./app.ts

/// <reference path="references.ts"/>
import Layout = require("./classes/Layout");

class Brooklyn {
    elementId: string;

    constructor(elementId: string) {
        this.elementId = elementId;
    }

    setupLayout() {
        console.log("building layout");
        var layout = new Layout(this.elementId);
        layout.build();
    }
}

./references.ts

/// <reference path="dfiles/jquery.d.ts"/>
/// <reference path="dfiles/jqueryui.d.ts"/>
/// <reference path="dfiles/jquery.ui.layout.d.ts"/>
/// <reference path="dfiles/node.d.ts" /> 

/// <reference path="classes/Layout.ts" /> 

./classes/Layout.ts

/// <reference path="../dfiles/jquery.d.ts"/>

    class Layout {
        static layoutOuter: JQueryLayout;
        elementId: string;
        westSelector: string;
        eastSelector: string;

        constructor(elementId: string) {
            this.elementId = elementId;
        }

        build() {
            console.log("init layout");
            this.westSelector = "body > .ui-layout-west"; // outer-west pane
            this.eastSelector = "body > .ui-layout-east"; // outer-east pane


            Layout.layoutOuter = $(this.elementId).layout();  // Error from this line
        }
    }

export = Layout;

I've added the jquery.d.ts reference to the Layout.ts file but that doesn't help either, neither does passing jQuery into the class as a reference. How does each separate class get access to jQuery?

1

There are 1 answers

0
Andrew Grothe On

My issue was using external TypeScript modules. Nw.js uses the node require to load node modules, not client side scripts like RequireJS does. Making my TypeScript modules internal solved the issue.

Also learned that external TypeScript modules do not share the same context as the main application (rather obvious now...) and that is why jquery wasn't getting recognized.