2017-04-11 51 views
1

我在Require.js模塊(AMD)中定義了一個函數和一個jQuery函數,我想導出它們。導出函數很簡單,但是如何導出jQuery函數?謝謝!如何在Require.js中導出自定義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> 

回答

0

你有什麼是jQuery插件。若要製作一個jQuery插件,其他代碼可以使用,設置$.fn.someFunc全部您需要做的。需要使用它的代碼只需將其列爲依賴項即可。例如:

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

沒有必要另外從您的AMD模塊導出它。

+0

對不起。我更新了這個問題,因爲我沒有詳細說明我的項目結構。我可以在main.js中需要我的someModule.js,而不是將'ejs'文件更改爲需要嗎?謝謝。 – cmal