---
title: "RequireJS和Backbone的集成"
author: "zhouyrt"
date: "2013-05-16T07:15:49Z"
tags: []
categories: ["Web前端"]
slug: "requirejs-backbone"
draft: false
lastmod: "2013-05-16T07:16:15Z"
id: 1870073
url: "https://snandy.iteye.com/blog/1870073"
---

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

 

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

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

 

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

[RequireJS 2.0](/blog/1552324%20)后提供了一个shim参数很好的解决了该问题。

 

示例目录  
![](http://dl.iteye.com/upload/attachment/0084/5491/3e1d0408-2b78-35b0-b6d9-bfa05415edfe.png)

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参数这里有介绍](http://www.cnblogs.com/snandy/archive/2012/06/04/2532997.html)。

这样配置后，当其它模块依赖于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。  
![](http://dl.iteye.com/upload/attachment/0084/5493/5c2d1cda-e261-3ec9-a42a-2f3de20d3513.png)  
 

 

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

 

 

 

相关：

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

[rb-2012-6-8.zip](http://files.cnblogs.com/snandy/rb-2012-6-8.zip)