RequireJS with jQuery Validation

一世执手 提交于 2019-12-01 21:15:08

You'll need to fix only one key in your config. Change this line:

'Scripts/jquery.validate.custom': ['jquery', 'Scripts/jquery.validate.unobtrusive']

With following:

'jquery.validate': ['jquery', 'Scripts/jquery.validate.unobtrusive']

And everything will work. This is because if you're using jquery.validate as a path you'll need to use same name in shim config to make all dependencies work correctly.

I believe the keys in the shim should match the names that you are require'ing in your module. Also I think it confuses the issue to use the name jquery.validate but then map it to custom.

To me the following structure would be more intuitive:

require.config({
    paths: {
        jquery: 'Scripts/jquery-1.8.3.min',
        jquery_validate: 'Scripts/jquery.validate'
        jquery_validate_unobtrusive: 'Scripts/jquery.validate.unobtrusive'
        jquery_validate_custom: 'Scripts/jquery.validate.custom'
    },
    shim: {
        jquery: {
           exports: ['jQuery', '$']
        },
        jquery_validate: ['jquery'],
        jquery_validate_unobtrusive: ['jquery_validate'],
        jquery_validate_custom: ['jquery_validate_unobtrusive']
    }
});

And then in your module, request the custom file:

define(['jquery', 'jquery_validate_custom'], function($) {
    alert('Yey!');
});

EDIT: thinking more about your original config and why it doesn't work: the issue you have is that you are trying to intersperse the use of full paths with module aliases in the shim section. RequireJS does not appear to work this way. It seems to be a one way resolution process:

Module names requested --> expand to any additional modules from shim config --> load the actual files based on path mapping

Whereas what you are trying to do is:

Module names requested (jquery.validate) --> resolve to actual files based on path mapping (jquery.validate.custom) --> expand to any additional modules from shim config --> resolve paths again

So for example, this works fine:

require.config({
  paths: {
    module1: 'module1file',
    module2: 'module2file',
    module3: 'module3file'
  },
  shim: {
    module3: ['module2'],
    module2: ['module1']
  }
});

require(['module3'], function( ) {
});

But this does not:

require.config({
  paths: {
    module1: 'module1file',
    module2: 'module2file',
    module3: 'module3file'
  },
  shim: {
    module3: ['module2'],
    module2file: ['module1']
  }
});

require(['module3'], function( ) {
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!