标题说明了一切。我正在处理的项目不是单个页面应用程序,也不是任何暗示任何复杂的数据流或AJAX请求,但我想保持我的代码清洁,避免错误以及不必要的函数唤起要在应用程序的页面上使用,所以我需要考虑它的架构。
想象一下,我们声明了应用程序的命名空间:
var MYAPP = MYAPP || {}
然后我将在该页面上初始化包含脚本的模块:
var currentSection = w.location.pathname;
switch (currentSection) {
case "/":
return MYAPP._home = new _Home();
case "contacts":
return MYAPP._contacts = new _Contacts();
default:
return console.log('Unknown template');
}
在上面的示例中,我使用URL的一部分来定义将要使用的模块,但我发现它不太可靠,因为如果我们更改URL,那么我们还需要相应地更改一些代码,否则它不会工作。另一种处理方法是在.php文件中定义模板,因此它可能是这样的:
<script>
var MYAPP = MYAPP || {};
MYAPP.template = 'contacts';
</script>
稍微更改我在上一个示例中使用的代码:
switch (MYAPP.template) {
case "/":
return MYAPP._home = new _Home();
case "contacts":
return MYAPP._contacts = new _Contacts();
default:
return console.log('Unknown template');
}
是否有更好的解决方案?如果信息很重要,我们在后端开发中使用Apache2 + PHP。
答案 0 :(得分:0)
将使用哪个模块
使用<script src=...
定义js文件时,将加载文件及其文件中的所有函数和类。我不知道你是如何完成只使用你的代码加载一个模块或类的 - 我只看到你正在定义哪些对象被创建。
这是我指定包含哪些js文件/类的方法。我使用三部分过程来包含基于定义
的php,css和js在index.php
我有
define("module1", true);
define("module2", true);
require("includes.php");
我的includes.php
文件与index.php在同一目录中(也在php路径中)。在其中我有:
<?php
require_once('paths.php');
if (defined("module1")){
require_once('module1.php');
?>
<script src="<?php echo APP_PATH ?>/js/module1.min.js"></script>
<?php
} else if (defined("module2")) {
require_once('module2.php');
?>
<script src="<?php echo APP_PATH ?>/js/module2.min.js"></script>
<?php
}
?>
在paths.php
中,位于根目录下方和php路径中,我有
<script>
var APP_PATH = "www.mysite.com";
</script>
这样,我的应用程序的路径信息可以在一个文件中维护。我还在这个文件中定义了我的php路径并为我的php文件添加了前缀,但这超出了你的要求。