使用Typescript,Knockout和Require的HTML组件-无法呈现HTML?

问题描述

我正在尝试学习组件驱动开发的工作方式,并且我遵循了https://knockoutjs.com/documentation/component-custom-elements.html包括与该主题相关的许多嵌套链接)中的文档,但是尽管TS / JS文件已正确加载了HTML组件永远不会呈现。

在这里您可以看到RequireJS正确加载了打字稿:

Login-User typescript loaded in browser

这是网页中的HTML组件:

HTML component

这是HTML“模板”中的内容

<div class="panel">
    <label>Username:</label>
    <input type="text" data-bind="Value: $component.Username()" />
    <br />
    <label>Password:</label>
    <input type="text" data-bind="Value: $component.Password()" />
    <br />
    <label>Valid:</label>
    <input type="text" data-bind="Value: $component.ValidUser()" />
</div>

这是HTML模板的注册

const componentName = "Login-User";
ko.components.unregister(componentName);
ko.components.register(componentName,{
    viewmodel: Loginviewmodel,template: { require: `text!/Views/Components/${componentName}.html` }
});

我在控制台中没有收到任何错误,但是在添加断点进行调试时,TS文件中的构造函数从未被击中,这表明我根本没有尝试渲染HTML组件?

我已经检查了所有文件路径是否正确并且已删除,然后重新编译TS文件生成JS文件以确保所有内容都是最新的,我认为我没有以某种方式正确配置了require,因此HTML组件永远不会实际已注册,但是由于没有记录错误,我对下一步的操作感到有些困惑!正如我之前所说,我已经阅读了有关Knockout以及RequireJS的文档,但是当在实现HTML组件时在Google上搜索问题时,我似乎只能获得Angular的结果。

任何有关如何确定问题的建议将不胜感激,甚至如果有任何有关如何使用Knockout / Require / Typescript / HTML组件的文档/指南,有人可以指出我的话,那就更好了! / p>

我想我已经提供了所有需要的东西,但是如果没有让我知道。

谢谢, 丹尼

解决方法

好几个小时的反复试验之后,我发现我遇到了一些问题,对于其他遇到此问题的人,请尝试以下解决方案:

  1. 我没有打电话给ko.applybindings();
import * as ko from "knockout";

export default class LoginViewModel {
    Username: KnockoutObservable<string>;
    Password: KnockoutObservable<string>;
    ValidUser: KnockoutComputed<boolean>;

    constructor(username: string,password: string) {
        this.Username = ko.observable(username);
        this.Password = ko.observable(password);

        this.computedMethods();
    }

    private computedMethods(): void {
        this.ValidUser = ko.pureComputed(() => {
            return this.Username() === "Danny" && this.Password() === "pasword";
        });
    }
}

const componentName = "login-user";
ko.components.register(componentName,{
    viewModel: LoginViewModel,template: { require: `text!Scripts/Typescript/${componentName}.html` }
});

ko.applyBindings(); << This is important as it actually binds the custom element i.e login-user params="username: 'Danny',password: 'none'"></login-user> and without it nothing will be rendered on the page
  1. 更正此问题后,我在尝试加载自定义元素时在控制台中看到404,尽管文件路径正确,但我发现解决此问题的最佳方法是将自定义元素与TS计数器放在同一文件夹中-部分:
Before:
template: { require: `text!/Views/Components/${componentName}.html` }

After:
template: { require: `text!Scripts/Typescript/${componentName}.html` }
  1. Google搜索建议安装以下nuget软件包,尽管我认为实际上仅需要require.text,如果它不能解决您的问题,则值得一试。 Require Packages
  1. 最初,我的组件使用驼峰式命名,即Login-User.ts和Login-User.html,我在某处读到它们应为小写字母,以成为有效的html'Tags'以及.ts和.html文件应该命名完全相同

希望这可以帮助其他遇到问题的人。