Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load prototype enhancements with require.js

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!

like image 332
AntonSack Avatar asked Aug 27 '26 11:08

AntonSack


1 Answers

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).

like image 140
Simon Smith Avatar answered Aug 30 '26 01:08

Simon Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!