如何从 KnockoutJS 中的组件节点获取组件的视图模型

cry*_*yss 6 javascript knockout.js

我有一个名为“我的组件”的组件:

ko.components.register('my-component', { 

    viewModel: function() {      
        return { title: 'title' };     
    },

    template: '<div>x</div>'

});
Run Code Online (Sandbox Code Playgroud)

我在这样的视图中使用这个组件:

<my-component params=""></my-component>
Run Code Online (Sandbox Code Playgroud)

有没有办法让组件的视图模型与这个 HTML 节点相关?ko.dataFor 不起作用:

ko.dataFor($('my-component').get(0)) // it doesn't return component's view model
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?

hai*_*770 4

尝试这个:

ko.dataFor($('my-component').get(0).firstChild);
Run Code Online (Sandbox Code Playgroud)