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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    <!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模块来使用了。

    1
    2
    3
    4
    5
    6
    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

  • 相关阅读:
    HDU 1018 Big Number
    UVa 10603 倒水问题
    UVa 12108 特别困的学生
    UVa 1590 IP网络(简单位运算)
    UVa 12325 宝箱
    UVa 253 骰子涂色
    UVa 815 洪水!
    springmvc(2)处理器设配器和映射器
    SpringMVC(1)
    MyBatis(10)逆向工程
  • 原文地址:https://www.cnblogs.com/zhepama/p/3053275.html
Copyright © 2011-2022 走看看