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

jQuery UI 部件库

核对 jQuery UI 部件库(Widget Factory)作为所有官方小部件可扩展基座的核心定位、有状态生命周期与四大专题学习路径。

学完这一章,你能够

  • 核对 jQuery UI 部件库(Widget Factory)作为所有官方小部件可扩展基座的核心定位、有状态生命周期与四大专题学习路径。

部件库(Widget Factory)的核心定位与能力

jQuery UI 部件库(Widget Factory)是一套可扩展的底层插件构建基础,所有官方 jQuery UI 小部件均建立在其之上。借助部件库开发插件,可以获得规范的状态管理机制,并自动获得暴露公共插件方法、在实例化之后动态读取与修改选项以及统一销毁清理等高频能力。

本单元围绕四个核心专题展开:如何通过部件库扩展已有小部件(Widget)、如何以插件或实例方式调用小部件方法、为什么以及何时选用部件库而非普通无状态插件,以及使用部件库从零构建有状态插件的完整步骤。本站离线 Playwright Chromium 实测注册 `custom.counter` 部件并初始化两个隔离节点(初始值 `10` 与 `50`):调用 `increment(5)` 并将 `step` 选项改为 `2` 后再次递增,`#c1` 文本依次更新为 `10` → `15` → `17` 而 `#c2` 保持 `50`;执行 `destroy` 后 `.custom-counter` 类与存储实例同步清空。

在离线 Chromium 中运行 Widget Factory 状态隔离、选项更新与销毁实验

含完整源码 · 228 行
展开查看收起
python
"""Offline Chromium lab for jQuery UI Ch11: Widget Factory overview."""
import json
from playwright.sync_api import sync_playwright

HTML = """<!doctype html>
<html>
<head><meta charset="utf-8"><title>Widget Factory Lab</title></head>
<body>
<div id="c1"></div>
<div id="c2"></div>
<script>
// Minimal faithful offline jQuery + Widget Factory core
(function(global) {
  const dataStore = new WeakMap();
  function getDataMap(el) {
    if (!dataStore.has(el)) dataStore.set(el, {});
    return dataStore.get(el);
  }
  function $(sel) {
    if (sel && sel._isJQ) return sel;
    const els = typeof sel === "string"
      ? Array.from(document.querySelectorAll(sel))
      : (sel instanceof Element ? [sel] : Array.isArray(sel) ? 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; },
    addClass(cls) { return this.each(function() { this.classList.add(...cls.split(/\\s+/).filter(Boolean)); }); },
    removeClass(cls) { return this.each(function() { this.classList.remove(...cls.split(/\\s+/).filter(Boolean)); }); },
    hasClass(cls) { return this.els[0] ? this.els[0].classList.contains(cls) : false; },
    text(val) {
      if (val === undefined) return this.els[0] ? this.els[0].textContent : "";
      return this.each(function() { this.textContent = String(val); });
    },
    data(key, val) {
      if (!this.els[0]) return undefined;
      const map = getDataMap(this.els[0]);
      if (val === undefined) return map[key];
      map[key] = val;
      return this;
    },
    removeData(key) {
      return this.each(function() { delete getDataMap(this)[key]; });
    }
  };
  $.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();
    },
    _create() {},
    option(key, value) {
      if (key === undefined) return $.extend({}, this.options);
      if (typeof key === "string") {
        if (value === undefined) return this.options[key];
        this._setOption(key, value);
      } else {
        for (const k of Object.keys(key)) this._setOption(k, key[k]);
      }
      return this;
    },
    _setOption(key, value) {
      this.options[key] = value;
      return this;
    },
    destroy() {
      this._destroy();
      this.element.removeData(this.widgetFullName);
    },
    _destroy() {}
  };
  $.widget = function(name, prototype) {
    const parts = name.split(".");
    const namespace = parts[0], widgetName = parts[1];
    const fullName = namespace + "-" + widgetName;
    $[namespace] = $[namespace] || {};
    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($.Widget.prototype), {
      constructor: Ctor,
      widgetName,
      namespace,
      widgetFullName: fullName,
      options: $.extend({}, prototype.options)
    }, prototype);
    $[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);

$.widget("custom.counter", {
  options: { value: 0, step: 1 },
  _create() {
    this.element.addClass("custom-counter").text(this.options.value);
  },
  increment(delta) {
    const inc = delta !== undefined ? delta : this.options.step;
    this.options.value += inc;
    this.element.text(this.options.value);
  },
  value() {
    return this.options.value;
  },
  _destroy() {
    this.element.removeClass("custom-counter").text("");
  }
});
</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("""() => {
                $("#c1").counter({ value: 10 });
                $("#c2").counter({ value: 50 });
                return {
                    c1Text: $("#c1").text(),
                    c2Text: $("#c2").text(),
                    c1Class: $("#c1").hasClass("custom-counter"),
                    isolated: $("#c1").data("custom-counter") !== $("#c2").data("custom-counter")
                };
            }""")
            exp1 = {"c1Text": "10", "c2Text": "50", "c1Class": True, "isolated": True}
            cases.append(dict(
                name="widget_factory_stateful_lifecycle",
                expected=exp1,
                actual=r1,
                passed=(r1 == exp1),
            ))

            r2 = page.evaluate("""() => {
                $("#c1").counter("increment", 5);
                const afterInc = $("#c1").counter("value");
                $("#c1").counter("option", "step", 2);
                $("#c1").counter("increment");
                return {
                    afterInc,
                    finalVal: $("#c1").counter("value"),
                    finalText: $("#c1").text(),
                    c2Unchanged: $("#c2").counter("value")
                };
            }""")
            exp2 = {"afterInc": 15, "finalVal": 17, "finalText": "17", "c2Unchanged": 50}
            cases.append(dict(
                name="widget_factory_method_and_option",
                expected=exp2,
                actual=r2,
                passed=(r2 == exp2),
            ))

            r3 = page.evaluate("""() => {
                $("#c1").counter("destroy");
                return {
                    c1HasClass: $("#c1").hasClass("custom-counter"),
                    c1Text: $("#c1").text(),
                    c1InstanceRemoved: $("#c1").data("custom-counter") === undefined,
                    c2StillActive: $("#c2").counter("value") === 50
                };
            }""")
            exp3 = {
                "c1HasClass": False,
                "c1Text": "",
                "c1InstanceRemoved": True,
                "c2StillActive": True,
            }
            cases.append(dict(
                name="widget_factory_destroy_cleanup",
                expected=exp3,
                actual=r3,
                passed=(r3 == exp3),
            ))
        finally:
            browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
核对两个计数器实例状态互不干扰(10 与 50),方法调用与 option 修改将 #c1 推进至 17,destroy 后移除类名、清空文本并释放实例引用。

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

本地运行

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

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

本章附件与实例包

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

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

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

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

统一了小部件的初始化与状态存储、公共方法暴露与调用约定、实例化后通过 option() 读写配置以及销毁清理流程,同时支持基于原型链扩展既有部件。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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