我最近开始从事Knockout的工作,并被分配去创建可在各种应用程序中使用的自定义组件。在创建组件时,我使用了驼峰式的命名方式,例如:“ datePicker
”。
ko.components.register("datePicker",{
viewModel: require('./components/date-picker-widget'),
template: require('raw!./components/date-picker-widget.html')
});
<datePicker params="{value:returnValue, initialValue:returnValue.initialValue}"></datePicker>
但这是渲染的:
因此,很明显,Knockout需要使用小写字母的组件名称(JSFiddle参考)。问题仍然是为什么?
我还看到了在React中对组件命名的类似限制,您必须在名称中仅以大写字母开头。
密钥在文档中:
默认情况下,Knockout假定您的自定义元素标记名称与使用ko.components.register注册的组件的名称完全对应。这种配置约定惯例策略对于大多数应用而言是理想的选择。
如果要使用不同的自定义元素标记名称,则可以重写getComponentNameForNode来控制它。例如,
ko.components.getComponentNameForNode = function(node) { var tagNameLower = node.tagName && node.tagName.toLowerCase(); if (ko.components.isRegistered(tagNameLower)) { // If the element's name exactly matches a preregistered // component, use that component return tagNameLower; } else if (tagNameLower === "special-element") { // For the element <special-element>, use the component // "MySpecialComponent" (whether or not it was preregistered) return "MySpecialComponent"; } else { // Treat anything else as not representing a component return null; } }
例如,如果您想控制已注册组件的哪个子集可以用作自定义元素,则可以使用此技术。
实际上,文档并没有完全与代码相提并论,因为它声称“完全对应”,而实际上在代码中,标签名仅小写,而注册不是。
无论如何,由于浏览器返回的tagName
是大写字母,因此上述代码仅在您的注册为小写字母时才有效。
因此,您可以datePicker
在视图中使用camelCased并将其注册为小写:
<datePicker></datePicker>
ko.components.register("datepicker",{
viewModel: function() { },
template: '<strong>DatePicker stub is showing!</strong>'
});
$(function() { ko.applyBindings({}); });
或者,您可以猴子修补注册功能:
<datePicker></datePicker>
var originalFn = ko.components.register;
ko.components.register = function(name, options) {
originalFn(name.toLowerCase(), options);
};
ko.components.register("datePicker",{
viewModel: function() { },
template: '<strong>DatePicker stub is showing!</strong>'
});
$(function() { ko.applyBindings({}); });
尽管我不确定这将如何稳定和跨浏览器兼容。
在任何情况下都无关紧要,因为您只是问“为什么”,就像那样。
我的建议:坚持的文档风格dash-cased-element-names
。
PS。您发布的屏幕快照是调试器如何渲染元素的方式,而不是Knockout或浏览器的方式。实际上,很可能如果您使用“查看源代码”,则会得到一个camelCased元素名称。完全确定您可以检查请求的原始内容。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句