How to access custom element in a Knockout component?

天涯浪子 提交于 2019-12-04 06:15:54

The custom element contains the component, it is not considered part of it. Just like the outer tag used in a foreach, template or with binding. If you want to style that tag, you have to add the bindings to style it. The component will fill its contents.

<hello data-bind="css: 'hello'"></hello>

However if you absolutely wanted to access the parent element, I suppose it's possible but I would not recommend it. The component should only be concerned with itself, not the container that contains it. This can (and will) cause problems if the element had any child nodes that also had bindings.

Use a factory function for your view model. It will have access to the component's info (which currently only includes the containing element element)

ko.components.register('hello', {
    viewModel: {
        createViewModel: function (params, componentInfo) {
            var element = componentInfo.element;
            ko.applyBindingsToNode(element, { css: 'hello' });
            return {};
        }
    },
    template: "<h1>hello world</h1>"
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!