gpt4 book ai didi

javascript - 限定 XHTML 中的 KnockOutJS 属性(通过 XML 命名空间)

转载 作者:行者123 更新时间:2023-11-28 16:05:06 28 4
gpt4 key购买 nike

我希望能够限定 XHTML 文档中的 KnockOutJS 属性。

这是我想做的:

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:ko="http://knockoutjs.com"> <!-- Supply the KnockOutJS namespace here -->
<head>
<script th:src="@{/js/lib/knockout-2.2.1.js}" src="../../js/lib/knockout-2.2.1.js"></script>
<!-- Remainder omitted... -->
</head>
<body>
<p>
My name is:
<span ko:data-bind="text: name"></span><!-- Problem line - KnockOut will ignore data-bind when it's qualified -->
</p>
</body>
</html>

上面的示例不起作用,因为 KnockOutJS 会忽略合格的 ko:data-bind。显然,如果我删除 ko: 那么它就可以工作。

有没有办法告诉 KnockOutJS 它是合格的以及限定符是什么?

我想要限定 KnockOutJS 属性的原因是:

  1. 验证。我收到很多关于未定义属性的验证警告(在 IDE 中)。
  2. 清晰。我们(谨慎地)使用 Thymeleaf 进行服务器端模板,并且 Thymeleaf 的工作方式与 KnockOut 类似,因为它也被指定为 HTML 属性。如果 Thymeleaf 用 th 限定,KnockOut 用 ko 限定,而标准 HTML 不限定,那就太好了。

谢谢!

最佳答案

Knockout 支持自定义绑定(bind)提供程序,可用于根据需要检索绑定(bind)。目前尚未有正式记录,但 described on Ryan Niemeyer's web site .

这是一个绑定(bind)提供程序,它扩展了内置提供程序以添加对 ko:data-bind 的支持。

var originalNodeHasBindings = ko.bindingProvider.instance.nodeHasBindings;
var originalGetBindings = ko.bindingProvider.instance.getBindings;
ko.utils.extend(ko.bindingProvider.instance, {
nodeHasBindings: function(node) {
if (node.nodeType == 1 && node.hasAttribute('ko:data-bind'))
return true;
return originalNodeHasBindings.call(this, node);
},
getBindings: function(node, bindingContext) {
if (node.nodeType == 1 && node.hasAttribute('ko:data-bind'))
return this.parseBindingsString(node.getAttribute('ko:data-bind'), bindingContext, node);
return originalGetBindings.call(this, node, bindingContext);
}
});

使用示例:http://jsfiddle.net/mbest/vSQkW/

关于javascript - 限定 XHTML 中的 KnockOutJS 属性(通过 XML 命名空间),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15374602/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com