1

我正在构建一个 CakePHP 应用程序。代码结构合理,因此每个控制器都被视为自己的迷你应用程序。

我将 jQuery 用于我的所有 JavaScript 功能。

我的问题是:构建 JavaScript 以便只有需要它的页面才有它的正确方法是什么?

每个应用程序我应该有单独的 js 文件吗?这样,App 1 的所有视图中都会包含 app1.js,App 2 将只有 app2.js,依此类推。然后我可以拥有一个具有所有通用功能的 main.js,它包含在所有页面中。

注意:我不想使用 JsHelper,也不想内联编写 JS。

4

1 回答 1

1

I would recommend you to take a look on this Autoload Plugin written by this marvelous guy ... oops, by me :).

So, using it you can easily split your javascript and even CSS into separate directories and you will have separate files included on each controller.

If you want to follow the trend - use RequireJS which give you ability to modularize your code and include only those pieces which you needed.

Although Autoload is my creation, I switched to RequireJS and I am quite happy with the results.

I will explain my approach with RequireJS.

What you need is the following code in the head section of your layout:

<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>

At the bottom of layout you need to include the requirejs file:

<script 
    data-main="<?php echo $this->Html->url('/'); ?>js/app" 
    src="<?php echo $this->Html->url('/'); ?>js/libs/requirejs.js">
</script>

The first piece just check if there is file for that specific controller and action in the folder like:

/wwwroot/js/actions/Posts/write.js

and if so, add a the var rPath which contain reference to that file.

Here is the example of RequireJS config file which I am using:

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]);
}

Finally if you need some javascript in your controller Posts and your action write you need to create a file in: /wwwroot/js/app/Posts/write.js with the following content:

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
});

Take a look on RequireJS documentation for more information.

Hope that helps.

于 2013-10-11T22:05:47.013 回答