如何使用RequireJS构建多个页面 [英] How to structure multiple pages with RequireJS

查看:277
本文介绍了如何使用RequireJS构建多个页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用RequireJS构建多个页面?像下面的示例一样,在app.js中声明每个类都是正确的做法吗?是否每个HTML文件都声明了<script data-main="src/main" src="src/require.js"></script>?

How to structure multiple pages with RequireJS? Is, like the following sample, declaring every class in app.js is the right thing to do? Has every html file to declare the <script data-main="src/main" src="src/require.js"></script>?

我要避免的是当用户到达网站的首页时加载所有脚本.

What I want to avoid is loading all the script when a user reach the first page of a site.

main.js定义所有外部依赖项:

require(
    {
        baseUrl:'/src'
    },
    [
        "require",
        "order!http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js",
        "order!http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js",
        "order!http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.6/underscore-min.js",
        "order!http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"
    ], 
    function (require) {
        require(["app"], function (app) {
            app.start();
        });
    }
);

app.js文件,定义每个组件:

define([ "product/ProductSearchView",
         "product/ProductCollection"
         ], function (ProductSearchView,
                      ProductCollection) {
         return {
             start: function() {
                  var products = new ProductCollection();
                  var searchView = new ProductSearchView({ collection: products });
                  products.fetch();
                  return {};
             }
        }
});

推荐答案

您可以在现有模块中要求文件.假设某人单击链接时,您可以触发执行以下操作的功能:

You can require files within your existing module. So say when someone clicks a link you could trigger a function that does the following:

// If you have a require in your other module
// The other module will execute its own logic
require(["module/one"], function(One) {
    $("a").click(function() {
        require(["new/module"]);
    });
});

// If you have a define in your other module
// You will need to add the variable to the require
// so you can access its methods and properties
require(["module/one"], function(One) {
    $("a").click(function() {
        require(["new/module"], function(NewModule) {
            NewModule.doSomething();
        });
    });
});

这篇关于如何使用RequireJS构建多个页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆