2

I am using require.js to load my modules which generally works fine. Nevertheless, I do have two additonal questions:

1) If you have a module that is like a helper class and defines additional methods for existing prototypes (such as String.isNullOrEmpty), how would you include them? You want to avoid using the reference to the module.

2) What needs to be changed to use jQuery, too. I understand that jQuery needs to be required but do I also need to pass on $?

Thanks!

4

2 に答える 2

10

1)ヘルパークラスのようなモジュールがあり、既存のプロトタイプの追加メソッド(String.isNullOrEmptyなど)を定義している場合、それらをどのように含めますか?モジュールへの参照を使用しないようにします。

プロトタイプを拡張する必要がある場合は、値を返さず、それを最後の引数として使用してくださいrequire

// helpers/string.js
define(function() {
    String.prototype.isNullOrEmpty = function() {
        // 
    }
});

// main.js
require(['moduleA', 'helpers/string'], function(moduleA) {

});

2)jQueryを使用するために変更する必要があるものも。jQueryが必要であることを理解していますが、$も渡す必要がありますか?

jQueryの唯一の要件は、パスを正しく構成することです

require.config({
    paths: {
        jquery: 'path/to/jquery'
    }
});

require(['jquery', 'moduleB'], function($, moduleB) {
    // Use $.whatever
});

私の意見では、jQueryがAMDをサポートしていないときに主に使用されていたため、 jQueryが組み込まれているバージョンのRequireJSを使用する必要はありません。

現在では、それを分離しておくことで、別のライブラリを簡単に交換できます(Zeptoを考えてみてください)。

于 2013-03-07T11:53:53.420 に答える
0

2/ jquery の場合は非常に簡単です。

require(["jquery", "jquery.alpha", "jquery.beta"], function($) {
    //the jquery.alpha.js and jquery.beta.js plugins have been loaded.
    $(function() {
        $('body').alpha().beta();
    });
});

require サイトの詳細: http://requirejs.org/docs/jquery.html#get

1/そのような拡張機能の私の開発では、requireモジュールコードなしでグローバルファイルでそれを行いました....そして、requireを使用してアプリに含めました...完璧ではありませんが、正常に動作します

global.js

myglobalvar ="";
(...other global stuff...)

myapp.js

// Filename: app.js
define([
    (...) 
    'metrix.globals'
], function(.....){
myApp = {
(...)
于 2013-03-07T10:02:28.873 に答える