我建议你看看这个了不起的家伙写的Autoload Plugin...哎呀,我写的:)。
因此,使用它,您可以轻松地将您的 javascript 甚至 CSS 拆分到单独的目录中,并且您将在每个控制器上包含单独的文件。
如果您想跟上潮流 - 请使用 RequireJS,它使您能够模块化代码并仅包含您需要的部分。
虽然 Autoload 是我的创作,但我切换到了 RequireJS,我对结果非常满意。
我将用 RequireJS 解释我的方法。
您需要在布局的 head 部分中添加以下代码:
<script>
<?php if(is_file(
__DIR__.'/../../webroot/js/action/'.
$this->request->params['controller'].'/'.
$this->request->params['action'].'.js'
)){ ?>
var rPath = root+'js/app/action/<?php echo
$this->request->params['controller'].'/'.
$this->request->params['action']; ?>';
<?php } ?>
</script>
在布局的底部你需要包含requirejs文件:
<script
data-main="<?php echo $this->Html->url('/'); ?>js/app"
src="<?php echo $this->Html->url('/'); ?>js/libs/requirejs.js">
</script>
第一部分只是检查文件夹中是否有该特定控制器和操作的文件,例如:
/wwwroot/js/actions/Posts/write.js
如果是这样,添加一个包含对该文件的引用的 var rPath。
这是我正在使用的 RequireJS 配置文件的示例:
require.config({
baseUrl: root+'js/',
paths: {
jquery : 'libs/jquery.min',
//...your convenient shortcuts
}
});
//That's where the magic happen
if(typeof(rPath) !== 'undefined'){
requirejs([rPath]);
}
最后,如果您的控制器 Posts 和您的操作写入需要一些 javascript,您需要在以下位置创建一个文件:
/wwwroot/js/app/Posts/write.js 内容如下:
define([
'jquery', //reference to jquery
'app/Posts/controller' //module which you wrote for controller specific functions.
//other libs or modules if needed.
], function($){
//your functions for wirite action
});
查看 RequireJS 文档了解更多信息。
希望对您有所帮助。