[英]How to improve separation of concerns in this Javascript code?
I have following code that uses html data attributes
instead of jquery class name selectors
as advised in Classnames for styling, data attributes for behavior . 我有以下代码,它们使用
html data attributes
代替jquery class name selectors
如Classnames中的样式建议,data属性中的行为 。 This code is working fine. 这段代码工作正常。 However, it refers the html5 data attributes in the javascript file.
但是,它引用javascript文件中的html5数据属性。
Example 例
$("[data-role='show-alert']").click(function () {
//and
textValue = $("[data-role='employee-name-text']").val();
QUESTION 题
What is the best way to avoid this reference of html5 data attributes in javascript file? 避免在javascript文件中引用html5数据属性的最佳方法是什么? (By using a model or something?)
(使用模型还是其他?)
Note: I am using Kendo UI
framework. 注意:我正在使用
Kendo UI
框架。
Head 头
<head>
<title>HTML 5 Test</title>
<script type="text/javascript" src="lib/kendo/js/jquery.min.js"></script>
<script type="text/javascript" src="lib/kendo/js/kendo.web.min.js"></script>
<script type="text/javascript">
//CONTROLLER File
var textValue = '';
function getEmployeeBusinessFunction() {
var currentEmployeeName = textValue;
alert(currentEmployeeName);
}
</script>
<script type="text/javascript">
$(document).ready(function () {
$("[data-role='show-alert']").click(function () {
//textValue = $('.myPersonTextbox').val();
textValue = $("[data-role='employee-name-text']").val();
//Call Business Function
getEmployeeBusinessFunction();
});
});
</script>
</head>
Body 身体
<body>
<form>
<input type="text" class='myPersonTextbox' name="personName" placeholder="Employee Name" data-role='employee-name-text' />
<button type="button" class='myButton' data-role='show-alert'>
Add</button>
</form>
</body>
REFERENCES 参考资料
It's fine to use thouse attributes even if they are part of HTML5 - thats what they are for. 即使thouse属性是HTML5的一部分,也可以使用thouse属性-这就是它们的用途。 Especially if no conflicts expected.
尤其是在没有冲突的情况下。
If you still want to get rid of naming conflicts, you may use namespaces with selectors like 如果您仍然想摆脱命名冲突,则可以将名称空间与选择器结合使用,例如
$('myns\\:[data-role='show-alert']')
...
<myns:button type="button" class='myButton' data-role='show-alert'>
to avoid selecting HTML5 attributes which are not related to your code. 以避免选择与您的代码无关的HTML5属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.