我以这种方式加载我的Knockout组件:
ko.components.register("example", {
viewModel: {require: "widgets/example"},
template: {require: "text!widgets/example.html"}
});
example.js
(非常简化):
"use strict";
define(["knockout"], function(ko) {
function ExampleWidgetViewModel(params) {
this.editedText = ko.observable("Example");
}
return ExampleWidgetViewModel;
});
和example.html
:
<div id="example-dlg", data-bind="text: editedText"></div>
该组件像往常一样被称为<example></example>
,一切都很完美。但我想访问DOM以消除模板中id
的需要。
尝试the method from the documentation将example.js
更改为:
"use strict";
define(["knockout"], function(ko) {
function ExampleWidgetViewModel(params, componentInfo) {
this.editedText = ko.observable("Example");
}
return {createViewModel: ExampleWidgetViewModel};
});
但它抱怨找不到editedText
。与此类其他变体相同的问题:
"use strict";
define(["knockout"], function(ko) {
function creaExample(params, componentInfo) {
let ExampleWidgetViewModel = (params) => {
this.editedText = ko.observable("Example");
}
return ExampleWidgetViewModel;
}
return {createViewModel: creaExample};
});
你能提供一个有效的例子吗?谢谢!
答案 0 :(得分:0)
没有什么比寻求帮助找到解决方案更好......我错误地调用了视图模型。正确的example.js
文件是:
"use strict";
define(["jquery", "knockout"], function($, ko) {
function factory(params, componentInfo) {
function ViewModel() {
// To show how to access the component external div
console.log($(componentInfo.element.firstChild).attr("id"));
// To show it can correctly access parameters
this.editedText = params.oneParameter;
}
return new ViewModel();
}
return {createViewModel: factory};
});