ami*_*min 6 javascript knockout.js knockout-components
看看这个场景:
ko.components.register('hello', {
viewModel: function() { },
template: "<h1>hello wrold</h1>"
});
Run Code Online (Sandbox Code Playgroud)
如果我使用<hello></hello>生成的html结果将是:
<hello><h1>hello world</h1></hello>
Run Code Online (Sandbox Code Playgroud)
但是如果我想要这个怎么办:
<hello class="hello"><h1>hello world</h1></hello>
Run Code Online (Sandbox Code Playgroud)
那么如何在组件中获得对自定义元素标记的引用?
Jef*_*ado 12
自定义元素包含组件,它不被视为其中的一部分.就像在使用的外层标签foreach,template或with结合.如果要为该标记设置样式,则必须添加绑定以对其进行样式设置.该组件将填充其内容.
<hello data-bind="css: 'hello'"></hello>
Run Code Online (Sandbox Code Playgroud)
但是,如果你绝对想要访问父元素,我想这是可能的,但我不推荐它.组件应仅关注自身,而不是包含它的容器.如果元素具有任何也具有绑定的子节点,则这可能(并且将会)导致问题.
为视图模型使用工厂函数.它可以访问组件的信息(目前只包含包含元素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>"
});
Run Code Online (Sandbox Code Playgroud)