如何在Require.js中导出自定义jQuery函数?

时间:2017-04-11 07:31:08

标签: jquery requirejs amd

我在Require.js模块(AMD)中定义了一个函数和一个jQuery函数,我想导出它们。导出函数很简单,但如何导出jQuery函数?谢谢!

// filename: someModule.js
define(function (require, exports) {

    function funcA () {}

    $.fn.someFunc = function( callback ) {
        return this.someFunc1(xxx, callback );
    };
    $.fn.extend({
        someFunc2: function () {}
    });
    exports.funcA = funcA;
    // how to export $.fn.someFunc, so I can use it in another module?
    // and how to export someFunc2?

});

我正在以这种方式使用此文件:

// another file: main.js
define(function (require, exports) {
    // this module is loaded by require.js
    var someModule = require('path/to/someModule');
    function init() {}
    exports.init = init;
});

并且该文件由服务器的.ejs文件呈现

<script type="text/javascript">
   require.config({
       baseUrl: '/asset',
       packages: [
        ...
       ]
   });
   require(['path/to/main.js'], function (main) {
       main.init();
   });
</script>

1 个答案:

答案 0 :(得分:0)

你拥有的是一个jQuery插件。要使其他代码可以使用jQuery插件,需要设置$.fn.someFunc all 。需要使用它的代码只需将其列为依赖项。类似的东西:

define(["jquery", "someFuncModule"], function ($) {
  $("some selector").someFunc(...);
});

无需再从AMD模块中导出它。

相关问题