如何使Typescript和Knockout.js与MVC应用程序一起工作

ebdffaop  于 2022-11-10  发布在  TypeScript
关注(0)|答案(1)|浏览(116)

将knockout .js viewModel绑定到MVC的问题。
我已经尝试遵循至少5教程,他们都看起来彼此不同,没有为我工作。我没有得到任何错误,而建立应用程序。
TS文件:

/// <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")

    }             
}

}

我的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>

我希望从公共测试或至少从简单的console.log获得绑定

yyyllmsg

yyyllmsg1#

为了使用导出和模块,需要使用webpack。如果你不需要这样的复杂性,那么试着只使用类而不使用任何导出/导入:

您的ts文件:

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

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

    }             
}

用法(在cshtml中):

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

看看我的小提琴:https://jsfiddle.net/koljada/dgnyspwa/3/

相关问题