requireJS define require
原文地址:http://blog.csdn.net/xiaogou56a/article/details/21340213
define 用来定义模块
require 用来加载模块
1
因为定义一个模块,可能会依赖其他模块,当然最简单的情况下是不依赖其他模块,这时就可以这样写:
- //Inside file my/shirt.js:
- define({
- color: "black",
- size: "unisize"
- });
官方解释:If the module does not have any dependencies, and it is just a collection of name/value pairs, then just pass an object literal to define():
2
定义一个模块,也可能需要先做一些setup工作,假设它也不依赖其他模块,这时可以这样写:
- //my/shirt.js now does setup work
- //before returning its module definition.
- define(function () {
- //Do setup work here
- return {
- color: "black",
- size: "unisize"
- }
- });
官方解释:If the module does not have dependencies, but needs to use a function to do some setup work, then define itself, pass a function to define():
3
定义一个模块,可能会很复杂,既依赖其它一些个模块,又需要一些setup工作,那么这个时候可以这样写:
- //my/shirt.js now has some dependencies, a cart and inventory
- //module in the same directory as shirt.js
- define(["./cart", "./inventory"], function(cart, inventory) {
- //return an object to define the "my/shirt" module.
- return {
- color: "blue",
- size: "large",
- addToCart: function() {
- inventory.decrement(this);
- cart.add(this);
- }
- }
- }
- );
被依赖的模块会作为参数一次传入到那个function中。
看官方解释:If the module has dependencies, the first argument should be an array of dependency names, and the second argument should be a definition function. The function will be called to define the module once all dependencies have loaded. The function should return an object that defines the module. The dependencies will be passed to the definition function as function arguments, listed in the same order as the order in the dependency array:
4
- //Explicitly defines the "foo/title" module:
- define("foo/title",
- ["my/cart", "my/inventory"],
- function(cart, inventory) {
- //Define foo/title object in here.
- }
- );
相信你一看便理解了,不过它里面的学问可以在没事的时候去看看官方的文档说明,也许很有意思的哦。
还有好多其他情况,但记住本质,define是用来定义模块的,require是用来加载模块的,整个库的开发考虑的情况比较多,比如:为了兼容以前的代码,为了适应某些库的使用,某些转换工具的使用,元编程的应用,等等。只要我们抓住本质,理解意思,具体的格式参考官网,只要别人用了,就肯定是合法的,就肯定是有根源的,今天到此为止。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。