井底之蛙

好记性不如烂笔头.菜鸟笔记.

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

http://www.requirejs.org/

http://www.requirejs.cn/

http://requirejs.readthedocs.org/en/1.0.1/

 

目录结构:

|-root
    |-demo
        |-js
            |-a.1.0.js
            |-a.1.1.js
            |-b.js
            |-c.js
            |-main.js
            |-util.js
        |-index.html
    |-libs
        |-requirejs
            |-require.js

文件下载

命名及代码都是随意写的,只为学习requirejs的写法.熟悉requirejs的用法.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>requirejs demo</title>
	<style>
		div {
			padding: 5px 10px;
		}
	</style>
	<script type="text/javascript" src="../libs/requirejs/require.js" data-main="./js/main.js"></script>
</head>
<body>
	 <div id="Main" style="width:600px;height:400px;border:1px red solid;"></div>
</body>
</html>
//main.js
require.config({
	baseUrl: 'js', // or ./js //baseUrl是从index.html开始计算的.
	map: {
		'b': {
			'a': 'a.1.0'
		},
		'c': {
			'a': 'a.1.1'
		}
	}
});

require(['b','c'], function(b, c){
	b();
	c();
});
//a.1.0.js
define([], function(){
	function add(a, b){
		return a+b;
	}
	function mul(a, b){
		return a*b;
	}
	return {
		'add': add,
		'mul': mul
	}
});
//a.1.1.js
define([], function(){
	function add(a, b){
		return a+b+1000;
	}
	function mul(a, b){
		return a*b*100;
	}
	return {
		'add': add,
		'mul': mul
	}
});
//b.js
define(['a', 'util'], function(aa, util){
	function test(a, b){
		util.log('Main', 'add: ' + aa.add(a, b));
		util.log('Main', 'mul: ' + aa.mul(a, b));
	}
	return function(){test.call(this, 2, 3)};
});
//c.js
define(['a', 'util'], function(aa, util){
	function test(a, b){
		util.log('Main', 'add: ' + aa.add(a, b));
		util.log('Main', 'mul: ' + aa.mul(a, b));
	}
	return function(){test.call(this, 2, 3)};
});
//util.js
define([], function(){
	// var __id = '';
	// var __tar = null;
	// function setId(id){
		// __id = id;
	// }
	// function _getEl(){
		// return document.getElementById(__id);
	// }
	function log(id, content){
		//var tar = __tar || __tar = _getEl();
		var tar = document.getElementById(id);
		var old = tar.innerHTML;
		tar.innerHTML = old + '<br>' + content;
	}
	return {
		'log': log
	};
});

开始时,把paths理解为map了.后来出现错误,再去查API时才发现.(而且将paths误写成了path)

开始时,我在b.js和c.js中都写了require.config({...}),并将path(s)分别设置为 'a': 'a.1.0' 和 'a': 'a.1.1' <- 这显然是错误. 

最开始时baseUrl也配置错误了.截图下来了.

 

posted on 2015-12-30 04:18  井底之蛙丶  阅读(401)  评论(0编辑  收藏  举报