【问题标题】:How to make Typescript and Knockout.js working with MVC application如何使 Typescript 和 Knockout.js 与 MVC 应用程序一起工作
【发布时间】:2019-11-20 21:14:51
【问题描述】:

将淘汰赛 .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 的绑定

【问题讨论】:

    标签: typescript model-view-controller knockout.js


    【解决方案1】:

    为了使用导出和模块,需要使用 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/

    【讨论】:

    • 我得到了控制台日志,但现在我得到了 ReferenceError: ko is not defined.
    • 您的淘汰赛脚本加载成功了吗?在做其他事情之前你能打电话给console.log(ko);吗?
    • 这似乎是问题所在 - ko 没有定义。会是我的参考补丁吗?
    • 您是从您的视图中调用 ko.applyBindings,而不是从 ts 文件中调用,对吧?
    • 我是,现在我使用了您答案中的代码。我从视图中注释掉了 ko.applyBinding。编辑:好的,这是我的错,我再次放弃你的答案并将 ko.binding 放在 cshtml 而不是 ts 文件中,一切都很好!谢谢
    猜你喜欢
    • 2012-06-18
    • 1970-01-01
    • 2020-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    相关资源
    最近更新 更多