Load prototype enhancements with require.js

让人想犯罪 __ 提交于 2019-12-11 03:17:39

问题


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!


回答1:


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.

If you need to extend prototypes then just don't return a value and use it as your last argument to require:

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

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

});

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 $?

The only requirement for jQuery is that you configure the path correct

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

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

In my opinion it's unnecessary to use the version of RequireJS that has jQuery built into it as this was primarily used when jQuery didn't support AMD.

Nowadays it does and keeping it separate allows you to swap another library out easily (think Zepto).




回答2:


2/ For jquery it's really simple :

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

More information on require site : http://requirejs.org/docs/jquery.html#get

1/ in my devs for such extension I did it in a global file without require module code.... and I include it in my app with require... not perfect, but it's work fine

global.js

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

myapp.js

// Filename: app.js
define([
    (...) 
    'metrix.globals'
], function(.....){
myApp = {
(...)


来源:https://stackoverflow.com/questions/15267524/load-prototype-enhancements-with-require-js

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