gpt4 book ai didi

javascript - 带有 RequireJs 和 TypeScript 的 KnockoutJs 组件

转载 作者:搜寻专家 更新时间:2023-10-30 21:00:27 24 4
gpt4 key购买 nike

在 Knockout 文档中配置组件时,我看到:

define(['knockout', 'text!./my-component.html'], function (ko, htmlString) {
function MyComponentViewModel(params) {
// Set up properties, etc.
}

// Return component definition
return { viewModel: MyComponentViewModel, template: htmlString };
});

我在我的项目中使用 TypeScript。如何在 TypeScript 中转换之前的代码?

我试过这个:

import ko = require("knockout");
import htmlString = require("text!./my-component.html");

class MyComponentViewModel {
}

但是 return 语句呢?

return { viewModel: MyComponentViewModel, template: htmlString };

最佳答案

我使用以下配置(这里看起来有点不知所措,但我希望这对您有所帮助):

“index.ts”,配置require.js:

require.config({
baseUrl: 'Scripts',

paths: {
//main libraries
jquery: '../Scripts/jquery-2.1.3',
knockout: '../Scripts/knockout-3.2.0.debug',

//shortcut paths
components: '../components',
modules: '../modules'
},

shim: {
jquery: {
exports: '$'
}
}
});

// ...... cutted
// here goes app entry point code

“modules”文件夹中的“application.ts”包含组件注册码:

import ko = require("knockout");

ko.components.register('like-widget', {
viewModel: { require: 'components/like-widget' },
template: { require: 'text!components/like-widget.html' }
});

“components”文件夹中的“like-widget.ts”,组件的 View 模型:

import ko = require("knockout");

class LikeWidgetViewModel {
constructor(params: { value: KnockoutObservable<string> }) {
this.chosenValue = params.value || ko.observable<string>();
}

chosenValue: KnockoutObservable<string>;

like() {
this.chosenValue('like');
}
dislike() {
this.chosenValue('dislike');
}
}

export = LikeWidgetViewModel;

“组件”文件夹中的“like-widget.html”:

<div class="like-or-dislike" data-bind="visible: !chosenValue()">
<button data-bind="click: like">Like it</button>
<button data-bind="click: dislike">Dislike it</button>
</div>

<div class="result" data-bind="visible: chosenValue">
You <strong data-bind="text: chosenValue"></strong> it.
And this was loaded from an external file.
</div>

关于javascript - 带有 RequireJs 和 TypeScript 的 KnockoutJs 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35427611/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com