如何访问Knockout组件中的自定义元素

如何访问Knockout组件中的自定义元素

本文介绍了如何访问Knockout组件中的自定义元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看看这种情况:

ko.components.register('hello', {
     viewModel: function() { },
     template: "<h1>hello wrold</h1>"
});

如果我使用<hello></hello>,则生成的html结果将是:

If I use <hello></hello> the generated html result will be:

<hello><h1>hello world</h1></hello>

但是,如果我想要这个:

But what if I want this:

<hello class="hello"><h1>hello world</h1></hello>

那么我如何获得对组件中自定义元素标签的引用?

Then how can I get a reference to the custom element tag in a component?

推荐答案

自定义元素包含该组件,但不认为它是该组件的一部分.就像foreachtemplatewith绑定中使用的外部标签一样.如果要为该标签设置样式,则必须添加绑定以对其进行样式设置.该组件将填充其内容.

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.

对视图模型使用工厂功能.它将有权访问组件的信息(当前仅包含包含元素element的信息)

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>"
});

这篇关于如何访问Knockout组件中的自定义元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 17:58