在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 };
答案 0 :(得分:2)
我使用以下配置(这似乎有点过头了,但我希望这会有所帮助):
" 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
" application.ts"来自" modules"文件夹包含组件注册码:
import ko = require("knockout");
ko.components.register('like-widget', {
viewModel: { require: 'components/like-widget' },
template: { require: 'text!components/like-widget.html' }
});
"像-widget.ts"来自"组件"文件夹,组件的视图模型:
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;
&#34;像-widget.html&#34;来自&#34;组件&#34;文件夹:
<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>