requirejs的结构;页面模块”;

Structure for requirejs "page module"

本文关键字:模块 结构 requirejs      更新时间:2023-09-26

在当前基于Asp.net WebForms的项目中,我们使用requirejs加载不同页面上的js模块。我只想检查以下是否是设置连接到特定页面功能的"模块"的正确方法。

对于一些需要更多"独特"脚本的特定页面,我们设置了所谓的"页面模块"。由于它不需要在自己的范围之外公开方法,所以我们不使用define,而是像这样指定它:

require(['main'], function () {
    require(['jquery', 'app/Ajax', 'underscore'], function ($, ajax, _) {
        _.templateSettings = {
            interpolate: /'{'{(.+?)'}'}/g,
            evaluate: /'{%(['s'S]+?)%'}/g,
            escape: /'{%-(['s'S]+?)%'}/g
        };
        var pageModule = function() {
            this.init();
        };
        pageModule.prototype.init = function () {
            var self = this;
            //init functionality
        };
        pageModule.prototype.method = function () {
            // function used by the pageModule itself
        }
        return new pageModule();
    });
});

然后在页面底部的html中,我们称之为require

<script>
    require(['pages/pageModule']);
</script>

试着四处寻找这样的模式,以确认这是利用功能的好方法,但没有发现太多。也许这是因为这不是一个好的使用方法,或者它被称为特定的东西。大多数示例都使用define,但由于该模块不应被任何其他函数使用,因此define似乎是多余的。

这是一个官方的多页示例,看起来很像您所拥有的:

https://github.com/requirejs/example-multipage

例如page1.js:

//Load common code that includes config, then load the app logic for this page.
requirejs(['./common'], function (common) {
    requirejs(['app/main1']);
});

在page1.html:中

<script data-main="js/page1" src="js/lib/require.js"></script>

(注:requirejs表示与require相同的功能)