Access Knockout component DOM from desired AMD viewModel
Silicon Valley
I load my Knockout components this way:
ko.components.register("example", {
viewModel: {require: "widgets/example"},
template: {require: "text!widgets/example.html"}
});
with example.js
(extremely simplified):
"use strict";
define(["knockout"], function(ko) {
function ExampleWidgetViewModel(params) {
this.editedText = ko.observable("Example");
}
return ExampleWidgetViewModel;
});
and example.html
:
<div id="example-dlg", data-bind="text: editedText"></div>
The component is called as usual <example></example>
and everything works fine. But I want to access the DOM to remove id
the need in the template. Try changing the method in the documentation to:example.js
"use strict";
define(["knockout"], function(ko) {
function ExampleWidgetViewModel(params, componentInfo) {
this.editedText = ko.observable("Example");
}
return {createViewModel: ExampleWidgetViewModel};
});
But it complains that it cannot be editedText
found. Other variations have the same problem:
"use strict";
define(["knockout"], function(ko) {
function creaExample(params, componentInfo) {
let ExampleWidgetViewModel = (params) => {
this.editedText = ko.observable("Example");
}
return ExampleWidgetViewModel;
}
return {createViewModel: creaExample};
});
Can you provide a working example? Thanks!
Silicon Valley
There's nothing better than asking for help finding a solution...I'm calling the viewmodel by mistake. The correct example.js
file is:
"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};
});