【问题标题】:Accessing Knockout component DOM from required AMD viewModel从所需的 AMD viewModel 访问 Knockout 组件 DOM
【发布时间】:2018-05-20 09:28:55
【问题描述】:

我以这种方式加载我的 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>

该组件像往常一样被称为&lt;example&gt;&lt;/example&gt;,并且一切正常。但我想访问 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};
});

您能提供一个工作示例吗?谢谢!

【问题讨论】:

    标签: knockout.js requirejs amd


    【解决方案1】:

    没有什么比寻求帮助以找到解决方案更好的了……我错误地调用了视图模型。正确的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};
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-25
      • 2012-02-29
      • 2014-09-07
      • 2021-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多