BokC
BokC

Reputation: 332

RequireJS : Load and start main ViewModel with TypeScrypt

I'm new on requireJs. I would like to load viewmodel from my main script : App.ts and get a new instance of my viewModel : LienPdtUfActVM.ts.

My App.ts file:

declare var jQuery: JQueryStatic;
declare var $test: any;

(function ($, $test) {
    if (typeof ($test.module.Livret) == 'object') {
        return;
    }

    $easily.module.Livret = {
        init: function (data) {
            var LienPdtUfAct = require(["./Livret/ViewModel/LienPdtUfActVM"]);
            ??????
        },
        destroy: function (applicationId) {
        }
    };
})(jQuery, $test);

My LienPdtUfActVM.ts :

export class LienPdtUfActVM {
    constructor() {
    }
}

I don't understand how to get this new instance.

My tsconfig.json :

{
    "compilerOptions": {
        "noImplicitAny": false,
        "noEmitOnError": true,
        "removeComments": false,
        "sourceMap": true,
        "target": "es2015",
        "module": "amd"
    },
    "compileOnSave": true
}

Try :

I try this :

import LienPdtUfAct = require('./Livret/ViewModel/LienPdtUfActVM');
....
new LienPdtUfAct.LienPdtUfActVM();

TypeScrypt compiler say ok but at the execution I get an "Uncaught Error: Mismatched anonymous define() module: function (require, exports, LienPdtUfAct) {..." error. The LienPdtUfActVM.js file was not loaded.

Upvotes: 1

Views: 43

Answers (2)

BokC
BokC

Reputation: 332

This code run :

$test.module.Livret = {
    init: function (data) {
        require(["./Livret/ViewModel/LienPdtUfActVM"], (LienPdtUfActVM) => {
            myInstance = new LienPdtUfActVM.LienPdtUfActVM();
        });
    },
    destroy: function (applicationId) {
    }
};

Upvotes: 0

Josh Wulf
Josh Wulf

Reputation: 4877

You do it like this:

declare var jQuery: JQueryStatic;
declare var $test: any;
var myInstance: any;

(function ($, $test) {
    if (typeof ($easily.module.Livret) == 'object') {
        return;
    }

    $easily.module.Livret = {
        init: function (data) {
            var LienPdtUfAct = require(["./Livret/ViewModel/LienPdtUfActVM"]);
            myInstance = new LienPdtUfAct.LienPdtUfAct;
        },
        destroy: function (applicationId) {
        }
    };
})(jQuery, $test);

I'm not sure what else you need to do to "start" it, because I'm not sure what framework it uses. But that is how you create an instance of it.

Upvotes: 0

Related Questions