RequireJS和Backbone的集成


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

 

這兩個輕量級的庫合起來使用確實能夠方便的構建大型應用程序。RequireJS填補了前端模塊化開發的空缺,Backbone采用MVC的分層結構很好的將程序各個部分解耦。

Backbone目前不支持AMD(曾經支持過),那么它只能作為普通的JS文件使用。它全局的標示符是Backbone,它還依賴於underscore,underscore的全局標示是下划線(_)。

 

因此,當我們使用AMD方式寫的模塊中使用Backbone時,得確保underscore和Backbone已經載入了。


RequireJS 2.0后提供了一個shim參數很好的解決了該問題。

 

示例目錄

 

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。


可以看到所有依賴的文件都依次下載了。在BaseRouter內部就可以使用Backbone了。

 

相關:

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

rb-2012-6-8.zip


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM