我无法弄清楚如何使用jQuery
加载jQueryValidate
,jQueryValidateUnobtrusive
和require.js
以及自定义验证规则,以便模块在准备好了。自定义规则被编写为模块(例如someCustomValidator.js
)。 jQueryValidateUnobtrusive
的工作方式是someCustomValidator
应该在jQuery
,jQueryValidate
和jQueryValidateUnobtrusive
加载之后但$.ready
被触发之前运行。第一个条件很简单,模块someCustomValidator
取决于jQuery
,jQueryValidate
和jQueryValidateUnobtrusive
。这是我被困的第二部分。 app.js
在关闭正文标记之前加载,因此在大多数情况下加载并运行someCustomValidator
时,domReady
已经被触发。如何设置依赖项以满足someCustomValidator should be run after jQuery, jQueryValidate and jQueryValidateUnobtrusive have been loaded but before $.ready is fired
的要求。我想过使用holdReady,但我不确定何时调用它以及在什么模块中。
实际定义validatorSetup.js
和someCustomValidator.js
不是很重要,但为了完整性,我将在下面提供基本设置。
HTML
...
...
<script src="SomePath/RequireJS/require.js"></script>
<script>
require(["app"]);
</script>
</body>
</html>
app.js
require([
"jquery",
"someCustomValidator",
"anotherCustomValidator"
], function ($,
someCustomValidator,
anotherCustomValidator) {
// Validators should be configured before dom ready.
someCustomValidator.init();
anotherCustomValidator.init();
$(function () {
// Stuff that should run after dom ready
someModule1.init();
someModule2.init();
});
});
validatorSetup.js
define("validatorSetup", ["jquery", "jquery-validate", "jquery-validate-unobtrusive"], (function ($) {
var validatorSetup = {
init: function() {
this.setDefaults();
},
setDefaults:function() {
this.setIgnore();
},
setIgnore: function() {
$.validator.setDefaults({
ignore: ":hidden, .ignore"
});
}
};
return validatorSetup;
}));
someCustomValidator.js
define("someCustomValidator", ["validatorSetup", "jquery", "jquery-validate", "jquery-validate-unobtrusive"], (function (validatorSetup, $) {
var someCustomValidator = {
init: function () {
validatorSetup.setIgnore();
this.setUpValidationRule();
},
setUpValidationRule: function () {
$.validator.unobtrusive.adapters.add(
"somerule",
["someprop", "rule", "ruleparam"],
function (options) {
options.rules["somerule"] = options.params;
options.messages["propertydependencyrule"] = options.message;
}
);
$.validator.addMethod(
"somerule",
function (value, element, params) {
var rule = params.rule;
var ruleParams = params.ruleparam;
//Some logic
return $.validator.methods[rule].call(this, value, element, ruleParams);
},
""
);
}
};
return someCustomValidator;
}));
答案 0 :(得分:0)
我以这种方式重新组织了依赖关系,并且dom ready已经准备就绪,直到它在加载someCustomValidator.js
之后发布。
app.js
require(["jquery"], function($) {
// Hold the domready
$.holdReady(true);
require([
"jquery",
"someCustomValidator",
"anotherCustomValidator"
], function ($,
someCustomValidator,
anotherCustomValidator) {
// Validators should be configured before dom ready.
someCustomValidator.init();
anotherCustomValidator.init();
// The custom validations have been attached.
// Now it is ok to let the dom ready to fire
$.holdReady(false);
$(function () {
// Stuff that should run after dom ready
someModule1.init();
someModule2.init();
});
});
});