zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    TortoiseGit保存用户名密码的方法
    nginx proxy优化
    tomcat优化
    mongodb 慢SQL查询
    iptables基础知识
    mongostat
    mongodb命令
    nginx libpcre.so.1: cannot open shared object file
    error while loading shared libraries: libmcrypt.so.4
    mongodb常见问题
  • 原文地址:https://www.cnblogs.com/snandy/p/2541827.html
Copyright © 2011-2022 走看看