Jquery 如何修改向$.fn添加函数的javascript文件以使用requirejs?

Jquery 如何修改向$.fn添加函数的javascript文件以使用requirejs?,jquery,requirejs,Jquery,Requirejs,我有一个javascript文件 $.fn.comments = function (method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.

我有一个javascript文件

$.fn.comments = function (method) {
    if (methods[method]) {
        return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === 'object' || !method) {
        return methods.init.apply(this, arguments);
    } else {
        $.error('Method ' + method + ' doesn not exists in jQuery.comments');
        return null;
    }
};
我看过从模块返回函数的简介requirejs教程

但是这个javascript向$.fn添加了函数,我如何更改这个文件以便使用requirejs?

简单的方法:

define(
  ['jQuery'],
  function ($) {
     $.fn.comments = .. /* do side effects as per the original */;
     return {
       /* ehh, others don't get a useful return,
          but we did our side-effect work upon jQuery (via $.fn) above */
     };
  });
如果这个模块有一个值可以在依赖模块中用作有用的东西,那么也可以返回一些东西,尽管jQuery插件的最大钩子是对
$.fn
产生副作用,这样说jQuery插件就可以作为
$(..).plugin访问。那么,一个依赖者:

define(
  ['jQuery', 'jQuery_comments'], /* require comment module */
  function ($, _comments) {      /* but don't care about value */
      /* and use plugin anyway as it's already been registered
         through a side-effect on $.fn */
      return {
        doStuff: function (..) {
          $(..).comments(..);
        }
      };
  });

或者,可以从依赖模块返回
注释
函数(方法){..}
),并在依赖模块中使用
$.fn.comments=comments
,但是我会像上面那样保留它,因为jQuery插件本身就是副作用。

在假设这不是您编写/维护的插件的情况下,我的建议是不要使用该插件,而是使用requirejs的一些配置功能来告诉它如何使用您的插件

requirejs.config({
    shim:{
        'jquery.comments': {               // module name
            deps: [ 'jquery' ],            // jquery dependency
            exports: 'jQuery.fn.comments'  // result of the module
        }
    }
});
添加以下requirejs.config将告诉requirejs如何处理插件

requirejs.config({
    shim:{
        'jquery.comments': {               // module name
            deps: [ 'jquery' ],            // jquery dependency
            exports: 'jQuery.fn.comments'  // result of the module
        }
    }
});
以下是有关此功能的更多文档:

有了这个配置,如果你最终想要使用一个更新版本的插件,你可以直接插入这个文件,它应该可以工作,但是如果你对这个文件进行更改,使它成为requirejs模式的模型,你需要一次又一次地进行更改,如果你以后选择升级插件的话。这两种方法都可以,但我更喜欢这种方法,因为它更适合长期的可维护性