为每个jQuery调用创建新类是最佳实践吗?


Is it best practice to create new class for each jQuery call?

我有一个目录树结构。每次我点击一个文件夹,jQuery.ajax触发并打开jquery.php文件。

这是我触发jQuery.ajax的javascript代码:

  jQuery('.directory').live('click',function() {
    // Get dir name clicked
    var dir = jQuery(this).find('span').html();
    // Update dir list
    getHTML('getDirList',dir, function(html){
      jQuery('#fileDirList').html(html);
    });
    // Update file list
    getHTML('getRowList',dir, function(html){
      jQuery('#fileList').html(html);
    });        
  });
  function getHTML(instance, dir, callback) {
      jQuery.ajax({
          type: "POST",
          url: "../wp-content/plugins/wp-filebrowser/jquery.php",
          dataType: 'html',
          data: {instance: instance, dir: dir},
          success: function(html){
              callback(html);
          },
          error: function(e) {
            callback('[Error] ' + e);
          }
      });
  }

在这个文件中,我在jQuery.php文件中有以下代码:

<?php
  class jQueryFactory {
  /**
   * Get and output directory list
   */  
  public function getDirList() {
    echo parent::getDirList();
  }

  /**
   * Get images and list them in row format
   */  
  public function getRowList() {
    echo parent::getRowList();
  }

  /**
   * Create new directory
   */  
  function createDir() {
    if(isset($_POST['new_dir'])) {
      $result = parent::createDir($_POST['new_dir']);
      echo $result;
    }
  }

  /**
   * Delete file
   */ 
  function deleteFile() {
    if(isset($_POST['file'])) {
      $file = $_POST['file'];
      parent::deleteImage($file);
    }
  }
}
// Does this work?
if(!isset($factory))
  $factory = new jQueryFactory();
switch($_POST['instance']) {
  case 'deleteImage'    : $factory->deleteFile(); break;
  case 'createDir'      : $factory->createDir(); break;
  case 'getDirList'     : $factory->getDirList($dir); break;
  case 'getRowList'     : $factory->getRowList($dir); break;
}   
?>

我的问题是:我每次点击都要触发这个函数吗?或者我可以触发一次,然后只调用同一用户会话中的各种函数?

您发出的每个Ajax请求都会在服务器端产生一个新的请求。

在PHP中对每个请求初始化类和配置变量是正常的,因此您所展示的方式很好,并且尝试在请求之间持久化jQueryFactory对象是不值得追求的想法。这应该也不是什么性能问题。

如果进程确实需要加速,可以考虑操作码缓存。

可以将$factory存储在$_SESSION变量中吗?

也许是这样的?(未经测试,我不熟悉jQueryFactory)

session_start();
$factory = isset($_SESSION["factory"]) ? $_SESSION["factory"] : makeNewFactory();
function makeNewFactory() {
  $fact = new jQueryFactory();
  $_SESSION["factory"] = $fact;
  return $fact;
}