Jquery RequireJS并使验证方法在js文件中可用
我有以下config.jsJquery RequireJS并使验证方法在js文件中可用,jquery,requirejs,Jquery,Requirejs,我有以下config.js require.config({ baseUrl: "/static/js", paths: { jquery: "src/jquery-1.7.2", jqueryui: "src/jquery-ui-1.10.0.custom/js/jquery-ui-custom", angular: "src/angular/1.0.4/angular", bootstrap: "bootstrap/js/bootstrap" }
require.config({
baseUrl: "/static/js",
paths: {
jquery: "src/jquery-1.7.2",
jqueryui: "src/jquery-ui-1.10.0.custom/js/jquery-ui-custom",
angular: "src/angular/1.0.4/angular",
bootstrap: "bootstrap/js/bootstrap"
},
shim: {
"jquery-validation-1.10.0/dist/jquery.validation.min" : {
deps: ["jquery"],
exports: "jquery.validation"
}
}
});
在我正在加载的一个js文件(名为signup.js
)中,我试图使jquery验证插件中的validate
方法可用
# File signup.js
define(["jquery"], function($) {
$('#beta_signup_form button[type=submit]').attr("disabled", "disabled");
$('#beta_signup_form').validate({
rules: {
name: {
required: true,
minlength: 4
},
email: {
required: true,
email: true
}
},
focusCleanup: true,
onkeyup: false,
errorElement: "span",
... the rest of the code ...
我在控制台中收到一个错误,上面写着uncaughttypeerror:Object[Object Object]没有方法“validate”
如何将
validate
方法传递给我的signup.js
脚本?您需要稍微调整一下配置。通常,在填充模块时,您还需要为其提供路径:
require.config({
baseUrl: "/static/js",
paths: {
jquery: "src/jquery-1.7.2",
jqueryui: "src/jquery-ui-1.10.0.custom/js/jquery-ui-custom",
angular: "src/angular/1.0.4/angular",
bootstrap: "bootstrap/js/bootstrap",
// Give validate a path
"jquery-validate": "jquery-validation-1.10.0/dist/jquery.validation.min"
},
shim: {
// Now shim it
"jquery-validate": {
deps: ["jquery"],
exports: "jquery.validation"
}
}
});
// Define it as a dependency. If the plugin doesn't return a value
// (most just augment the jQuery.fn) then no need to pass an argument
// to your callback.
define(["jquery", "jquery-validate"], function($) {
// module code
});
如果插件未导出值,则可以进一步缩短代码:
shim: {
"jquery-validate": ["jquery"]
}
官方文档中的更多示例-这似乎加载了jquery.validate.js,但现在,jquery.validate.js本身给了我一个错误,即
uncaughttypeerror:无法读取未定义的属性“fn”。知道为什么会这样吗?我发现垫片在过去最好是修补的,这取决于插件的编写方式。我决定用一个“自我定义”来包装它。我承认这并不理想,但工作可靠。我只是花了一些时间试图让这个解决方案起作用,但却被卡住了。读了这些评论后,我有点困惑。。。所以这个答案实际上不起作用?我必须基本上分叉插件并将其包装在define中?如果是这种情况,您应该使用该信息编辑答案。啊,我想我可以通过删除配置中的exports
属性来解决我的问题。一旦代码加载了它,它就会添加到全局jQuery对象中,默认情况下,该对象可以通过require-jQuery.js访问,因此我认为它没有必要。