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

时间:2014-09-13 14:10:31

标签: javascript knockout.js knockout-components

看看这个场景:

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

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

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

但如果我想要这个怎么办:

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

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

1 个答案:

答案 0 :(得分:12)

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

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

但是如果你绝对想要访问父元素,我认为它是可能的,但我不推荐它。组件应仅关注自身,而不是包含它的容器。如果元素具有任何也具有绑定的子节点,则这可能(并且将会)导致问题。

为视图模型使用工厂函数。它可以访问组件的信息(目前只包含包含元素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>"
});