萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 物件導向寫法最佳實踐:模組化、命名空間、事件委派

標準引入方式

<script src="/libs/jquery/jquery.js"></script>

推薦模組模式

var qiyiPlugin = {
  init: function (parentNode) {
    var self = this;
    self.parentNode = parentNode;

    // 事件委派:區域重新整理
    self.parentNode.on('refresh', function () {
      self.qiyiList();
    });
  },

  qiyiList: function () {
    var self = this;
    self.getQiyiList(function (result) {
      if (result.qiyiList) {
        self.qiyiHtml1();
        self.displayQiyiList(result.qiyiList);
      } else alert('無法取得資料');
    });
  },

  displayQiyiList: function (list) {
    var self = this, top = '#zong_qiyi';
    $(top).find('#qiyi_control_panel[data-data]').remove();

    var tpl = $(top).find('#qiyi_control_panel');
    $.each(list, function (i, item) {
      var row = tpl.clone()
        .data('data', item)
        .attr('id', i + 1)
        .find('#name').html(item.name).end()
        .find('#level').html(item.level).end()
        .find('#maxLevel').html(item.maxLevel).end()
        .find('#exp').html(item.exp + '/' + item.needExp).end()
        .find('#desc1').html(item.desc1).end()
        .find('#upgrade').click(function () {
          var info = $(this).closest('table').data('data');
          self.clickToUpgradeQiyi(info, function (res) {
            if (!res.success) alert(res.fail.desc1);
            else { growingPlugin.playerTopData(); self.parentNode.trigger('refresh'); }
          });
        }).end();

      tpl.before(row.show());
    });
  },

  qiyiHtml1: function () {
    var html = "<table id='qiyi_control_panel' class='table table-bordered table-hover' style='display:none;width:500px'>" +
      "<tr><td>名稱:</td><td id=name></td></tr>" +
      "<tr><td>當前等級:</td><td id=level></td></tr>" +
      "<tr><td>最大等級:</td><td id=maxLevel></td></tr>" +
      "<tr><td>exp:</td><td id=exp></td></tr>" +
      "<tr><td>描述:</td><td id=desc1></td></tr>" +
      "<tr><td><button id='upgrade' class='btn btn-link'>升級</button></td></tr>" +
      "</table>";
    $('#zong_qiyi').html(html);
  },

  clickToUpgradeQiyi: function (info, cb) {
    toolsPlugin.play('operation=upgradeQiyi&qiyiName=' + info.name, cb);
  },

  getQiyiList: function (cb) {
    toolsPlugin.play('operation=getQiyiList', cb);
  }
};

// 啟動
$(function () { qiyiPlugin.init($('#zong_qiyi')); });

關鍵優點

  1. 單一職責:每個方法專注單一功能
  2. 資料綁定:`.data('data', item)` 避免全域變數污染
  3. 事件委派:動態新增的按鈕自動生效
  4. 模板複製:`clone()` + `before()` 高效渲染列表
  5. 回呼模式:非同步資料處理清晰明確

進階建議

  • 搭配 ES6 Class 或 TypeScript 重構更易維護
  • 將 HTML 模板抽離至 `