有朋友留言RequireJS如何与Backbone集合使用。

 

这两个轻量级的库合起来使用确实能够方便的构建大型应用程序。RequireJS填补了前端模块化开发的空缺,Backbone采用MVC的分层结构很好的将程序各个部分解耦。

Backbone目前不支持AMD(曾经支持过),那么它只能作为普通的JS文件使用。它全局的标示符是Backbone,它还依赖于underscore,underscore的全局标示是下划线(_)。

 

因此,当我们使用AMD方式写的模块中使用Backbone时,得确保underscore和Backbone已经载入了。


RequireJS 2.0后提供了一个shim参数很好的解决了该问题。

 

示例目录

RequireJS和Backbone的集成

 

js目录中有underscore.js,backbone.js。其中cache.js不依赖于Backbone,BaseRouter.js依赖。

 

index.html如下

<!doctype html>
<html>
	<head>
		<title>RequireJS和Backbone集成</title>
		<meta charset="utf-8"/>
		<script src="require.js"></script>
		<script>
			require.config({
				baseUrl: 'js',
				shim: {
					'backbone': {
						deps: ['underscore'],
						exports: 'Backbone'
					}
				}
			});
			require(['BaseRouter'], function(baseRouter) {
			});
		</script>
 	</head>
 	<body>
 	</body>
</html>

  

注意,require.config配置了shim参数,shim参数这里有介绍

这样配置后,当其它模块依赖于Backbone(如BaseRouter),它会顺序下载underscore.js和backbone.js。

BaseRouter内就可以把backbone当成AMD模块来使用了。

define(['backbone', 'cache'], function(Backbone, cache){
	// todo with Backbone and other module 
	console.log(Backbone);
	console.log(cache);
	return {};
})

把目录rb放到apache或其它web服务器上,访问index.html。

RequireJS和Backbone的集成


可以看到所有依赖的文件都依次下载了。在BaseRouter内部就可以使用Backbone了。

 

相关:

http://stackoverflow.com/questions/10933541/how-to-nested-use-require-js-with-backbone-js

rb-2012-6-8.zip

相关文章:

  • 2022-12-23
  • 2022-02-08
  • 2021-11-25
  • 2021-10-27
  • 2022-01-01
  • 2021-07-24
  • 2021-12-09
猜你喜欢
  • 2022-12-23
  • 2021-05-04
  • 2021-08-22
  • 2021-05-20
  • 2022-12-23
相关资源
相似解决方案