public
Last active

Using require.js map configuration to façade module in a way to always load relevant plugins and localization.

  • Download Gist
config.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
require.config({
 
paths: {
jquery : "../../vendors/js/jquery/jquery",
validate : "../../vendors/js/jquery.validation/jquery.validate",
validate_fr : "../../vendors/js/jquery.validation/messages_fr"
},
map: {
// Façade modules or swap them for another one
"*": {
"validate" : "facade-validator"
},
"facade/validator": {
"validate": "validate"
},
"validate_fr": {
"validate": "validate"
}
}
 
});
facade-validator.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
define([
"jquery",
"validate",
"validate_fr" // Get the good localization dictionnary - I'll usually use a require plugin here
], function( $ ) {
 
// Adding custom validation methods
$.validator.addMethod( "phone", function( value ) {
return value.match(/^([01]{1})?[\-\.\s]?\(?(\d{3})\)?[\-\.\s]?(\d{3})[\-\.\s]?(\d{4})\s?((?:#|ext\.?\s?|x\.?\s?){1}(?:\d+)?)?$/i);
}, function() {
return "Please give a valid phone number";
});
 
return $.validator;
});
main.js
JavaScript
1 2 3 4 5 6
define([
"jquery",
"validate"
], function( $ ) {
$("form").validate();
});

For the i18n, I usually use require.replace loader plugin so I don't have to specify each locale in the map config, and to load/build only relevant locales without any headaches.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.