使用require.js加载原型增强功能 [英] Load prototype enhancements with require.js

查看:75
本文介绍了使用require.js加载原型增强功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用require.js加载我的模块,该模块通常运行良好.但是,我确实有两个附加问题:

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

1)如果您有一个类似于帮助器类的模块,并且为现有原型(例如String.isNullOrEmpty)定义了其他方法,您将如何包括它们?您要避免使用对该模块的引用.

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)使用jQuery也需要更改.我了解需要jQuery,但是我还需要传递$吗?

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

谢谢!

推荐答案

1)如果您有一个类似于帮助程序类并定义的模块 现有原型的其他方法(例如 String.isNullOrEmpty),您将如何包含它们?你想避免 使用对模块的引用.

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.

如果您需要扩展原型,那么就不要返回任何值并将其用作require的最后一个参数:

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)使用jQuery也需要更改.我明白那个 jQuery是必需的,但我还需要传递$吗?

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

对jQuery的唯一要求是您配置正确的路径

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
});

我认为没有必要使用内置jQuery的RequireJS版本,因为该版本主要用于jQuery不支持AMD.

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.

如今,它确实做到了,并且将其分开保存,使您可以轻松地换出另一个库(请考虑使用Zepto).

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

这篇关于使用require.js加载原型增强功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆