蓝色天空.知识 · 实践 · 创造
我的收藏
jQuery UI 教程目录 43章
jQuery UI / LEARN BY DOING

jQuery UI 扩展小部件

核对通过 $.widget() 继承父部件、重载方法与 _super/_superApply 调用、原位重定义小部件、多态隔离边界及单实例方法定制。

学完这一章,你能够

  • 核对通过 $.widget() 继承父部件、重载方法与 _super/_superApply 调用、原位重定义小部件、多态隔离边界及单实例方法定制。

创建小部件扩展与自定义原型方法

借助 jQuery UI 部件库,开发者既可以在现有小部件基础上扩展出功能更强的复合部件,也能仅针对局部交互做细微调整。动手扩展前,需先掌握部件库的基本创建流程与实例工作机制。

通过向 `$.widget()` 传入带命名空间的小部件名与原型对象即可创建新部件(例如 `"custom.superDialog"`)。若要继承既有部件,只需将父部件构造函数(如 `$.ui.dialog`)作为第二个参数置于名称与原型对象之间;当原型为空对象时,子部件与父部件在行为上等价,仅命名空间与名称不同。随后在末尾的原型对象上添加方法(例如 `red()` 中通过 `this.element.css("color", "red")` 改色),部件库会自动把 `this` 绑定到当前小部件实例。本站 Chromium 实测显示,`$("<div>I am red</div>").superDialog().superDialog("red")` 后元素计算色值为 `rgb(255, 0, 0)` 且对话框保持打开(`isOpen === true`)。

扩展已有方法与 _super() / _superApply()

当需要在原部件方法上增改逻辑时,只需在原型对象中定义同名方法(例如重载 `dialog` 的 `open()` 记录日志)。但直接覆盖会替换原型链上的原始实现——若不回调用父类逻辑,对话框默认打开行为将丢失,元素不会显示在屏幕上。为此,部件库提供了 `_super()` 与 `_superApply()` 两个内置调用桥接方法。

`_super()` 与 `_superApply()` 均用于调用父部件中的同名方法,二者的参数传递语义对应 `Function.prototype.call()` 与 `Function.prototype.apply()`:`_super(key, value)` 接收离散参数列表,`_superApply(arguments)` 接收单个参数数组(或类数组对象)。本站离线 Chromium 实测对比:未调用 `_super()` 的 `silentDialog` 在 `open()` 后仍处于隐藏态(`display: none`、`isOpen: false`),而调用 `this._super()` 的 `superDialog` 既记录日志又正常展开(`display: block`、`isOpen: true`),并在 `_setOption` 中顺利将 `title="Updated"`、`width=420` 写入选项。

重定义小部件、多态边界与单实例定制

自 jQuery UI 1.9 起支持直接重定义已有小部件:无需另起新名,只需将原名称与原构造函数一并传入 `$.widget("ui.dialog", $.ui.dialog, { ... })`,即可在保留 `_super()` 访问原方法的前提下增强所有后续 `dialog` 实例。本站实测重定义 `ui.dialog` 的 `open()` 后,连续创建两个对话框共触发两次 `redefined-open` 记录且二者均处于打开状态。

在多态交互上需注意一项关键限制:父部件的插件方法无法用于调用子部件元素上的方法。若元素是以 `.superDialog()` 初始化的,执行 `dialog.superDialog("close")` 可正常关闭,但调用父插件 `dialog.dialog("close")` 不会生效。本站实测确认前者成功将 `isOpen` 置为 `false`,后者因未在元素上初始化 `ui-dialog` 而抛出 `cannot call methods on dialog prior to initialization`。

修改原型对象会影响该小部件的全部实例;若只需一次性定制某个独立实例的行为,可先通过 `.data("ui-dialog")` 取出该元素绑定的实例引用,再用常规 JavaScript 属性赋值直接覆盖其方法(如重写 `dialogInstance.close`)。本站实测对两个 `dialog` 实例执行 `$( ":data(ui-dialog)" ).dialog("close")` 时,仅被单独覆盖的实例触发了自定义 `close` 日志(计数 `1`),另一实例仍按原型逻辑正常关闭。

在离线 Chromium 中验证小部件继承、_super/_superApply、原位重定义与单实例定制

含完整源码 · 336 行
展开查看收起
python
"""Offline Chromium lab for jQuery UI Ch12: Extending Widgets with the Widget Factory."""
import json
from playwright.sync_api import sync_playwright

HTML = """<!doctype html>
<html>
<head><meta charset="utf-8"><title>Widget Extend Lab</title></head>
<body>
<div id="host"></div>
<script>
(function(global) {
  const dataStore = new WeakMap();
  const allTracked = new Set();
  function getDataMap(el) {
    if (!dataStore.has(el)) dataStore.set(el, {});
    return dataStore.get(el);
  }
  function $(sel) {
    if (sel && sel._isJQ) return sel;
    let els = [];
    if (typeof sel === "string") {
      if (sel.trim().startsWith("<")) {
        const tmp = document.createElement("div");
        tmp.innerHTML = sel.trim();
        els = Array.from(tmp.children);
      } else if (sel.startsWith(":data(") && sel.endsWith(")")) {
        const key = sel.slice(6, -1);
        els = Array.from(allTracked).filter(el => getDataMap(el)[key] !== undefined);
      } else {
        els = Array.from(document.querySelectorAll(sel));
      }
    } else if (sel instanceof Element) {
      els = [sel];
    } else if (Array.isArray(sel)) {
      els = sel;
    }
    return Object.assign(Object.create($.fn), { _isJQ: true, length: els.length, els });
  }
  $.fn = {
    each(fn) { this.els.forEach((el, i) => fn.call(el, i, el)); return this; },
    appendTo(target) {
      const t = typeof target === "string" ? document.querySelector(target) : target;
      return this.each(function() { t.appendChild(this); });
    },
    css(prop, val) {
      if (val === undefined) return this.els[0] ? getComputedStyle(this.els[0])[prop] : "";
      return this.each(function() { this.style[prop] = val; });
    },
    data(key, val) {
      if (!this.els[0]) return undefined;
      const map = getDataMap(this.els[0]);
      if (val === undefined) return map[key];
      allTracked.add(this.els[0]);
      map[key] = val;
      return this;
    }
  };
  $.extend = function(target, ...sources) {
    const out = target || {};
    for (const src of sources) {
      if (!src) continue;
      for (const k of Object.keys(src)) out[k] = src[k];
    }
    return out;
  };
  $.Widget = function() {};
  $.Widget.prototype = {
    _createWidget(options, element) {
      this.element = $(element);
      this.options = $.extend({}, this.options, options);
      this.element.data(this.widgetFullName, this);
      this._create();
      this._init();
    },
    _create() {},
    _init() {},
    option(key, value) {
      if (typeof key === "string") {
        if (value === undefined) return this.options[key];
        this._setOption(key, value);
      } else if (key) {
        for (const k of Object.keys(key)) this._setOption(k, key[k]);
      }
      return this;
    },
    _setOption(key, value) {
      this.options[key] = value;
      return this;
    }
  };
  $.widget = function(name, base, prototype) {
    if (!prototype) {
      prototype = base;
      base = $.Widget;
    }
    const [namespace, widgetName] = name.split(".");
    const fullName = namespace + "-" + widgetName;
    $[namespace] = $[namespace] || {};
    const baseProto = base.prototype;
    const proxiedProto = {};
    for (const prop of Object.keys(prototype)) {
      const value = prototype[prop];
      if (typeof value === "function") {
        proxiedProto[prop] = (function(key, fn) {
          const _super = function(...args) {
            return baseProto[key].apply(this, args);
          };
          const _superApply = function(args) {
            return baseProto[key].apply(this, args);
          };
          return function(...args) {
            const prevSuper = this._super;
            const prevSuperApply = this._superApply;
            this._super = _super;
            this._superApply = _superApply;
            try {
              return fn.apply(this, args);
            } finally {
              this._super = prevSuper;
              this._superApply = prevSuperApply;
            }
          };
        })(prop, value);
      } else {
        proxiedProto[prop] = value;
      }
    }
    function Ctor(options, element) {
      if (!(this instanceof Ctor)) return new Ctor(options, element);
      if (arguments.length) this._createWidget(options, element);
    }
    Ctor.prototype = Object.assign(Object.create(baseProto), {
      constructor: Ctor,
      widgetName,
      namespace,
      widgetFullName: fullName,
      options: $.extend({}, baseProto.options, prototype.options)
    }, proxiedProto);
    $[namespace][widgetName] = Ctor;
    $.fn[widgetName] = function(options, ...args) {
      if (typeof options === "string") {
        let returnValue = this;
        this.each(function() {
          const inst = $(this).data(fullName);
          if (!inst) throw new Error("cannot call methods on " + widgetName + " prior to initialization");
          if (typeof inst[options] !== "function" || options.startsWith("_")) {
            throw new Error("no such method '" + options + "'");
          }
          const res = inst[options](...args);
          if (res !== inst && res !== undefined) returnValue = res;
        });
        return returnValue;
      }
      return this.each(function() {
        const inst = $(this).data(fullName);
        if (inst) inst.option(options || {});
        else new Ctor(options, this);
      });
    };
  };
  global.$ = global.jQuery = $;
})(window);

// Base $.ui.dialog
$.widget("ui.dialog", {
  options: { autoOpen: true, title: "Dialog", width: 300 },
  _create() {
    this._isOpen = false;
    this.element.css("display", "none");
  },
  _init() {
    if (this.options.autoOpen) this.open();
  },
  open() {
    this._isOpen = true;
    this.element.css("display", "block");
  },
  close() {
    this._isOpen = false;
    this.element.css("display", "none");
  },
  isOpen() {
    return this._isOpen;
  }
});
</script>
</body>
</html>
"""


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


def main():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        try:
            page = browser.new_page()
            page.set_content(HTML)

            r1 = page.evaluate("""() => {
                $.widget("custom.superDialog", $.ui.dialog, {
                    red() {
                        this.element.css("color", "red");
                    }
                });
                const el = $("<div>I am red</div>").appendTo("#host").superDialog().superDialog("red");
                return {
                    color: el.css("color"),
                    isOpen: el.superDialog("isOpen"),
                    isWidgetInstance: el.data("custom-superDialog") instanceof $.custom.superDialog
                };
            }""")
            exp1 = {"color": "rgb(255, 0, 0)", "isOpen": True, "isWidgetInstance": True}
            cases.append(dict(name="extend_base_widget_and_custom_method", expected=exp1, actual=r1, passed=(r1 == exp1)))

            r2 = page.evaluate("""() => {
                const logs = [];
                $.widget("custom.silentDialog", $.ui.dialog, {
                    open() { logs.push("silent-open"); }
                });
                const silent = $("<div>S</div>").appendTo("#host").silentDialog();
                const silentIsOpen = silent.silentDialog("isOpen");
                const silentDisplay = silent.css("display");

                const setOptionCalls = [];
                $.widget("custom.superDialog", $.ui.dialog, {
                    open() {
                        logs.push("super-open");
                        return this._super();
                    },
                    _setOption(key, value) {
                        setOptionCalls.push(key + ":" + value);
                        this._super(key, value);
                        this._superApply(arguments);
                    }
                });
                const dlg = $("<div>OK</div>").appendTo("#host").superDialog();
                dlg.superDialog("option", "title", "Updated");
                dlg.superDialog("option", "width", 420);
                return {
                    logs,
                    silentIsOpen,
                    silentDisplay,
                    superIsOpen: dlg.superDialog("isOpen"),
                    superDisplay: dlg.css("display"),
                    title: dlg.superDialog("option", "title"),
                    width: dlg.superDialog("option", "width"),
                    setOptionCalls
                };
            }""")
            exp2 = {
                "logs": ["silent-open", "super-open"],
                "silentIsOpen": False,
                "silentDisplay": "none",
                "superIsOpen": True,
                "superDisplay": "block",
                "title": "Updated",
                "width": 420,
                "setOptionCalls": ["title:Updated", "width:420"],
            }
            cases.append(dict(name="override_vs_super_and_super_apply", expected=exp2, actual=r2, passed=(r2 == exp2)))

            r3 = page.evaluate("""() => {
                const logs = [];
                $.widget("ui.dialog", $.ui.dialog, {
                    open() {
                        logs.push("redefined-open");
                        return this._super();
                    }
                });
                const d1 = $("<div>A</div>").appendTo("#host").dialog();
                const d2 = $("<div>B</div>").appendTo("#host").dialog();
                return {
                    logCount: logs.length,
                    logs,
                    bothOpen: d1.dialog("isOpen") && d2.dialog("isOpen")
                };
            }""")
            exp3 = {"logCount": 2, "logs": ["redefined-open", "redefined-open"], "bothOpen": True}
            cases.append(dict(name="redefine_existing_widget", expected=exp3, actual=r3, passed=(r3 == exp3)))

            r4 = page.evaluate("""() => {
                $.widget("custom.polyDialog", $.ui.dialog, {});
                const el = $("<div>P</div>").appendTo("#host").polyDialog();
                el.polyDialog("close");
                const closedByChild = !el.polyDialog("isOpen");
                let parentError = "";
                try {
                    el.dialog("close");
                } catch (e) {
                    parentError = e.message;
                }
                return { closedByChild, parentError };
            }""")
            exp4 = {
                "closedByChild": True,
                "parentError": "cannot call methods on dialog prior to initialization",
            }
            cases.append(dict(name="widget_polymorphism_isolation", expected=exp4, actual=r4, passed=(r4 == exp4)))

            r5 = page.evaluate("""() => {
                const customLogs = [];
                const dA = $("<div>InstA</div>").appendTo("#host").dialog();
                const instA = dA.data("ui-dialog");
                instA.close = function() {
                    customLogs.push("custom-close");
                };
                const dB = $("<div>InstB</div>").appendTo("#host").dialog();
                $(":data(ui-dialog)").dialog("close");
                return {
                    customCloseCount: customLogs.length,
                    dAStillOpenBecauseCustomSkippedSuper: dA.dialog("isOpen"),
                    dBClosedByPrototype: !dB.dialog("isOpen")
                };
            }""")
            exp5 = {
                "customCloseCount": 1,
                "dAStillOpenBecauseCustomSkippedSuper": True,
                "dBClosedByPrototype": True,
            }
            cases.append(dict(name="single_instance_customization", expected=exp5, actual=r5, passed=(r5 == exp5)))
        finally:
            browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
核对 superDialog.red() 渲染 rgb(255, 0, 0)、不调 _super() 时对话框保持隐藏而调用后正常打开、原位重定义作用于双实例、父插件调用子实例报错,以及单实例覆盖仅命中目标实例。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a954.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:jQuery UI

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a954.zip

下载课程关联工程包:jQuery UI

课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a916.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

`_super()` 类似 `call()` 接收参数列表,`_superApply()` 类似 `apply()` 接收参数数组或 `arguments`;子部件实例按自身全名键存储于元素数据中,父部件插件查找的是父部件键名,故无法跨插件分派方法。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习